home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2009 May / maximum-cd-2009-05.iso / DiscContents / Firefox Setup 3.0.6.exe / nonlocalized / components / nsSearchService.js < prev    next >
Encoding:
Text File  |  2009-01-19  |  108.1 KB  |  3,209 lines

  1. //@line 40 "e:\fx19rel\WINNT_5.2_Depend\mozilla\browser\components\search\nsSearchService.js"
  2.  
  3. const Ci = Components.interfaces;
  4. const Cc = Components.classes;
  5. const Cr = Components.results;
  6.  
  7. const PERMS_FILE      = 0644;
  8. const PERMS_DIRECTORY = 0755;
  9.  
  10. const MODE_RDONLY   = 0x01;
  11. const MODE_WRONLY   = 0x02;
  12. const MODE_CREATE   = 0x08;
  13. const MODE_APPEND   = 0x10;
  14. const MODE_TRUNCATE = 0x20;
  15.  
  16. // Directory service keys
  17. const NS_APP_SEARCH_DIR_LIST  = "SrchPluginsDL";
  18. const NS_APP_USER_SEARCH_DIR  = "UsrSrchPlugns";
  19. const NS_APP_SEARCH_DIR       = "SrchPlugns";
  20. const NS_APP_USER_PROFILE_50_DIR = "ProfD";
  21.  
  22. // Search engine "locations". If this list is changed, be sure to update
  23. // the engine's _isDefault function accordingly.
  24. const SEARCH_APP_DIR = 1;
  25. const SEARCH_PROFILE_DIR = 2;
  26. const SEARCH_IN_EXTENSION = 3;
  27.  
  28. // See documentation in nsIBrowserSearchService.idl.
  29. const SEARCH_ENGINE_TOPIC        = "browser-search-engine-modified";
  30. const QUIT_APPLICATION_TOPIC     = "quit-application";
  31.  
  32. const SEARCH_ENGINE_REMOVED      = "engine-removed";
  33. const SEARCH_ENGINE_ADDED        = "engine-added";
  34. const SEARCH_ENGINE_CHANGED      = "engine-changed";
  35. const SEARCH_ENGINE_LOADED       = "engine-loaded";
  36. const SEARCH_ENGINE_CURRENT      = "engine-current";
  37.  
  38. const SEARCH_TYPE_MOZSEARCH      = Ci.nsISearchEngine.TYPE_MOZSEARCH;
  39. const SEARCH_TYPE_OPENSEARCH     = Ci.nsISearchEngine.TYPE_OPENSEARCH;
  40. const SEARCH_TYPE_SHERLOCK       = Ci.nsISearchEngine.TYPE_SHERLOCK;
  41.  
  42. const SEARCH_DATA_XML            = Ci.nsISearchEngine.DATA_XML;
  43. const SEARCH_DATA_TEXT           = Ci.nsISearchEngine.DATA_TEXT;
  44.  
  45. // File extensions for search plugin description files
  46. const XML_FILE_EXT      = "xml";
  47. const SHERLOCK_FILE_EXT = "src";
  48.  
  49. // Delay for lazy serialization (ms)
  50. const LAZY_SERIALIZE_DELAY = 100;
  51.  
  52. const ICON_DATAURL_PREFIX = "data:image/x-icon;base64,";
  53.  
  54. // Supported extensions for Sherlock plugin icons
  55. const SHERLOCK_ICON_EXTENSIONS = [".gif", ".png", ".jpg", ".jpeg"];
  56.  
  57. const NEW_LINES = /(\r\n|\r|\n)/;
  58.  
  59. // Set an arbitrary cap on the maximum icon size. Without this, large icons can
  60. // cause big delays when loading them at startup.
  61. const MAX_ICON_SIZE   = 10000;
  62.  
  63. // Default charset to use for sending search parameters. ISO-8859-1 is used to
  64. // match previous nsInternetSearchService behavior.
  65. const DEFAULT_QUERY_CHARSET = "ISO-8859-1";
  66.  
  67. const SEARCH_BUNDLE = "chrome://browser/locale/search.properties";
  68. const BRAND_BUNDLE = "chrome://branding/locale/brand.properties";
  69.  
  70. const OPENSEARCH_NS_10  = "http://a9.com/-/spec/opensearch/1.0/";
  71. const OPENSEARCH_NS_11  = "http://a9.com/-/spec/opensearch/1.1/";
  72.  
  73. // Although the specification at http://opensearch.a9.com/spec/1.1/description/
  74. // gives the namespace names defined above, many existing OpenSearch engines
  75. // are using the following versions.  We therefore allow either.
  76. const OPENSEARCH_NAMESPACES = [
  77.   OPENSEARCH_NS_11, OPENSEARCH_NS_10,
  78.   "http://a9.com/-/spec/opensearchdescription/1.1/",
  79.   "http://a9.com/-/spec/opensearchdescription/1.0/"
  80. ];
  81.  
  82. const OPENSEARCH_LOCALNAME = "OpenSearchDescription";
  83.  
  84. const MOZSEARCH_NS_10     = "http://www.mozilla.org/2006/browser/search/";
  85. const MOZSEARCH_LOCALNAME = "SearchPlugin";
  86.  
  87. const URLTYPE_SUGGEST_JSON = "application/x-suggestions+json";
  88. const URLTYPE_SEARCH_HTML  = "text/html";
  89.  
  90. // Empty base document used to serialize engines to file.
  91. const EMPTY_DOC = "<?xml version=\"1.0\"?>\n" +
  92.                   "<" + MOZSEARCH_LOCALNAME +
  93.                   " xmlns=\"" + MOZSEARCH_NS_10 + "\"" +
  94.                   " xmlns:os=\"" + OPENSEARCH_NS_11 + "\"" +
  95.                   "/>";
  96.  
  97. const BROWSER_SEARCH_PREF = "browser.search.";
  98.  
  99. const USER_DEFINED = "{searchTerms}";
  100.  
  101. // Custom search parameters
  102. //@line 141 "e:\fx19rel\WINNT_5.2_Depend\mozilla\browser\components\search\nsSearchService.js"
  103. const MOZ_OFFICIAL = "official";
  104. //@line 145 "e:\fx19rel\WINNT_5.2_Depend\mozilla\browser\components\search\nsSearchService.js"
  105. const MOZ_DISTRIBUTION_ID = "org.mozilla";
  106.  
  107. const MOZ_PARAM_LOCALE         = /\{moz:locale\}/g;
  108. const MOZ_PARAM_DIST_ID        = /\{moz:distributionID\}/g;
  109. const MOZ_PARAM_OFFICIAL       = /\{moz:official\}/g;
  110.  
  111. // Supported OpenSearch parameters
  112. // See http://opensearch.a9.com/spec/1.1/querysyntax/#core
  113. const OS_PARAM_USER_DEFINED    = /\{searchTerms\??\}/g;
  114. const OS_PARAM_INPUT_ENCODING  = /\{inputEncoding\??\}/g;
  115. const OS_PARAM_LANGUAGE        = /\{language\??\}/g;
  116. const OS_PARAM_OUTPUT_ENCODING = /\{outputEncoding\??\}/g;
  117.  
  118. // Default values
  119. const OS_PARAM_LANGUAGE_DEF         = "*";
  120. const OS_PARAM_OUTPUT_ENCODING_DEF  = "UTF-8";
  121. const OS_PARAM_INPUT_ENCODING_DEF   = "UTF-8";
  122.  
  123. // "Unsupported" OpenSearch parameters. For example, we don't support
  124. // page-based results, so if the engine requires that we send the "page index"
  125. // parameter, we'll always send "1".
  126. const OS_PARAM_COUNT        = /\{count\??\}/g;
  127. const OS_PARAM_START_INDEX  = /\{startIndex\??\}/g;
  128. const OS_PARAM_START_PAGE   = /\{startPage\??\}/g;
  129.  
  130. // Default values
  131. const OS_PARAM_COUNT_DEF        = "20"; // 20 results
  132. const OS_PARAM_START_INDEX_DEF  = "1";  // start at 1st result
  133. const OS_PARAM_START_PAGE_DEF   = "1";  // 1st page
  134.  
  135. // Optional parameter
  136. const OS_PARAM_OPTIONAL     = /\{(?:\w+:)?\w+\?\}/g;
  137.  
  138. // A array of arrays containing parameters that we don't fully support, and
  139. // their default values. We will only send values for these parameters if
  140. // required, since our values are just really arbitrary "guesses" that should
  141. // give us the output we want.
  142. var OS_UNSUPPORTED_PARAMS = [
  143.   [OS_PARAM_COUNT, OS_PARAM_COUNT_DEF],
  144.   [OS_PARAM_START_INDEX, OS_PARAM_START_INDEX_DEF],
  145.   [OS_PARAM_START_PAGE, OS_PARAM_START_PAGE_DEF],
  146. ];
  147.  
  148. // The default engine update interval, in days. This is only used if an engine
  149. // specifies an updateURL, but not an updateInterval.
  150. const SEARCH_DEFAULT_UPDATE_INTERVAL = 7;
  151.  
  152. // Returns false for whitespace-only or commented out lines in a
  153. // Sherlock file, true otherwise.
  154. function isUsefulLine(aLine) {
  155.   return !(/^\s*($|#)/i.test(aLine));
  156. }
  157.  
  158. /**
  159.  * Prefixed to all search debug output.
  160.  */
  161. const SEARCH_LOG_PREFIX = "*** Search: ";
  162.  
  163. /**
  164.  * Outputs aText to the JavaScript console as well as to stdout.
  165.  */
  166. function DO_LOG(aText) {
  167.   dump(SEARCH_LOG_PREFIX + aText + "\n");
  168.   var consoleService = Cc["@mozilla.org/consoleservice;1"].
  169.                        getService(Ci.nsIConsoleService);
  170.   consoleService.logStringMessage(aText);
  171. }
  172.  
  173. //@line 233 "e:\fx19rel\WINNT_5.2_Depend\mozilla\browser\components\search\nsSearchService.js"
  174.  
  175. /**
  176.  * Otherwise, don't log at all by default. This can be overridden at startup
  177.  * by the pref, see SearchService's _init method.
  178.  */
  179. var LOG = function(){};
  180.  
  181. //@line 241 "e:\fx19rel\WINNT_5.2_Depend\mozilla\browser\components\search\nsSearchService.js"
  182.  
  183. function ERROR(message, resultCode) {
  184.   NS_ASSERT(false, SEARCH_LOG_PREFIX + message);
  185.   throw resultCode;
  186. }
  187.  
  188. /**
  189.  * Ensures an assertion is met before continuing. Should be used to indicate
  190.  * fatal errors.
  191.  * @param  assertion
  192.  *         An assertion that must be met
  193.  * @param  message
  194.  *         A message to display if the assertion is not met
  195.  * @param  resultCode
  196.  *         The NS_ERROR_* value to throw if the assertion is not met
  197.  * @throws resultCode
  198.  */
  199. function ENSURE_WARN(assertion, message, resultCode) {
  200.   NS_ASSERT(assertion, SEARCH_LOG_PREFIX + message);
  201.   if (!assertion)
  202.     throw resultCode;
  203. }
  204.  
  205. /**
  206.  * Ensures an assertion is met before continuing, but does not warn the user.
  207.  * Used to handle normal failure conditions.
  208.  * @param  assertion
  209.  *         An assertion that must be met
  210.  * @param  message
  211.  *         A message to display if the assertion is not met
  212.  * @param  resultCode
  213.  *         The NS_ERROR_* value to throw if the assertion is not met
  214.  * @throws resultCode
  215.  */
  216. function ENSURE(assertion, message, resultCode) {
  217.   if (!assertion) {
  218.     LOG(message);
  219.     throw resultCode;
  220.   }
  221. }
  222.  
  223. /**
  224.  * Ensures an argument assertion is met before continuing.
  225.  * @param  assertion
  226.  *         An argument assertion that must be met
  227.  * @param  message
  228.  *         A message to display if the assertion is not met
  229.  * @throws NS_ERROR_INVALID_ARG for invalid arguments
  230.  */
  231. function ENSURE_ARG(assertion, message) {
  232.   ENSURE(assertion, message, Cr.NS_ERROR_INVALID_ARG);
  233. }
  234.  
  235. function loadListener(aChannel, aEngine, aCallback) {
  236.   this._channel = aChannel;
  237.   this._bytes = [];
  238.   this._engine = aEngine;
  239.   this._callback = aCallback;
  240. }
  241. loadListener.prototype = {
  242.   _callback: null,
  243.   _channel: null,
  244.   _countRead: 0,
  245.   _engine: null,
  246.   _stream: null,
  247.  
  248.   QueryInterface: function SRCH_loadQI(aIID) {
  249.     if (aIID.equals(Ci.nsISupports)           ||
  250.         aIID.equals(Ci.nsIRequestObserver)    ||
  251.         aIID.equals(Ci.nsIStreamListener)     ||
  252.         aIID.equals(Ci.nsIChannelEventSink)   ||
  253.         aIID.equals(Ci.nsIInterfaceRequestor) ||
  254.         aIID.equals(Ci.nsIBadCertListener2)   ||
  255.         aIID.equals(Ci.nsISSLErrorListener)   ||
  256.         // See FIXME comment below
  257.         aIID.equals(Ci.nsIHttpEventSink)      ||
  258.         aIID.equals(Ci.nsIProgressEventSink)  ||
  259.         false)
  260.       return this;
  261.  
  262.     throw Cr.NS_ERROR_NO_INTERFACE;
  263.   },
  264.  
  265.   // nsIRequestObserver
  266.   onStartRequest: function SRCH_loadStartR(aRequest, aContext) {
  267.     LOG("loadListener: Starting request: " + aRequest.name);
  268.     this._stream = Cc["@mozilla.org/binaryinputstream;1"].
  269.                    createInstance(Ci.nsIBinaryInputStream);
  270.   },
  271.  
  272.   onStopRequest: function SRCH_loadStopR(aRequest, aContext, aStatusCode) {
  273.     LOG("loadListener: Stopping request: " + aRequest.name);
  274.  
  275.     var requestFailed = !Components.isSuccessCode(aStatusCode);
  276.     if (!requestFailed && (aRequest instanceof Ci.nsIHttpChannel))
  277.       requestFailed = !aRequest.requestSucceeded;
  278.  
  279.     if (requestFailed || this._countRead == 0) {
  280.       LOG("loadListener: request failed!");
  281.       // send null so the callback can deal with the failure
  282.       this._callback(null, this._engine);
  283.     } else
  284.       this._callback(this._bytes, this._engine);
  285.     this._channel = null;
  286.     this._engine  = null;
  287.   },
  288.  
  289.   // nsIStreamListener
  290.   onDataAvailable: function SRCH_loadDAvailable(aRequest, aContext,
  291.                                                 aInputStream, aOffset,
  292.                                                 aCount) {
  293.     this._stream.setInputStream(aInputStream);
  294.  
  295.     // Get a byte array of the data
  296.     this._bytes = this._bytes.concat(this._stream.readByteArray(aCount));
  297.     this._countRead += aCount;
  298.   },
  299.  
  300.   // nsIChannelEventSink
  301.   onChannelRedirect: function SRCH_loadCRedirect(aOldChannel, aNewChannel,
  302.                                                  aFlags) {
  303.     this._channel = aNewChannel;
  304.   },
  305.  
  306.   // nsIInterfaceRequestor
  307.   getInterface: function SRCH_load_GI(aIID) {
  308.     return this.QueryInterface(aIID);
  309.   },
  310.  
  311.   // nsIBadCertListener2
  312.   notifyCertProblem: function SRCH_certProblem(socketInfo, status, targetSite) {
  313.     return true;
  314.   },
  315.  
  316.   // nsISSLErrorListener
  317.   notifySSLError: function SRCH_SSLError(socketInfo, error, targetSite) {
  318.     return true;
  319.   },
  320.  
  321.   // FIXME: bug 253127
  322.   // nsIHttpEventSink
  323.   onRedirect: function (aChannel, aNewChannel) {},
  324.   // nsIProgressEventSink
  325.   onProgress: function (aRequest, aContext, aProgress, aProgressMax) {},
  326.   onStatus: function (aRequest, aContext, aStatus, aStatusArg) {}
  327. }
  328.  
  329.  
  330. /**
  331.  * Used to verify a given DOM node's localName and namespaceURI.
  332.  * @param aElement
  333.  *        The element to verify.
  334.  * @param aLocalNameArray
  335.  *        An array of strings to compare against aElement's localName.
  336.  * @param aNameSpaceArray
  337.  *        An array of strings to compare against aElement's namespaceURI.
  338.  *
  339.  * @returns false if aElement is null, or if its localName or namespaceURI
  340.  *          does not match one of the elements in the aLocalNameArray or
  341.  *          aNameSpaceArray arrays, respectively.
  342.  * @throws NS_ERROR_INVALID_ARG if aLocalNameArray or aNameSpaceArray are null.
  343.  */
  344. function checkNameSpace(aElement, aLocalNameArray, aNameSpaceArray) {
  345.   ENSURE_ARG(aLocalNameArray && aNameSpaceArray, "missing aLocalNameArray or \
  346.              aNameSpaceArray for checkNameSpace");
  347.   return (aElement                                                &&
  348.           (aLocalNameArray.indexOf(aElement.localName)    != -1)  &&
  349.           (aNameSpaceArray.indexOf(aElement.namespaceURI) != -1));
  350. }
  351.  
  352. /**
  353.  * Safely close a nsISafeOutputStream.
  354.  * @param aFOS
  355.  *        The file output stream to close.
  356.  */
  357. function closeSafeOutputStream(aFOS) {
  358.   if (aFOS instanceof Ci.nsISafeOutputStream) {
  359.     try {
  360.       aFOS.finish();
  361.       return;
  362.     } catch (e) { }
  363.   }
  364.   aFOS.close();
  365. }
  366.  
  367. /**
  368.  * Wrapper function for nsIIOService::newURI.
  369.  * @param aURLSpec
  370.  *        The URL string from which to create an nsIURI.
  371.  * @returns an nsIURI object, or null if the creation of the URI failed.
  372.  */
  373. function makeURI(aURLSpec, aCharset) {
  374.   var ios = Cc["@mozilla.org/network/io-service;1"].
  375.             getService(Ci.nsIIOService);
  376.   try {
  377.     return ios.newURI(aURLSpec, aCharset, null);
  378.   } catch (ex) { }
  379.  
  380.   return null;
  381. }
  382.  
  383. /**
  384.  * Gets a directory from the directory service.
  385.  * @param aKey
  386.  *        The directory service key indicating the directory to get.
  387.  */
  388. function getDir(aKey) {
  389.   ENSURE_ARG(aKey, "getDir requires a directory key!");
  390.  
  391.   var fileLocator = Cc["@mozilla.org/file/directory_service;1"].
  392.                     getService(Ci.nsIProperties);
  393.   var dir = fileLocator.get(aKey, Ci.nsIFile);
  394.   return dir;
  395. }
  396.  
  397. /**
  398.  * The following two functions are essentially copied from
  399.  * nsInternetSearchService. They are required for backwards compatibility.
  400.  */
  401. function queryCharsetFromCode(aCode) {
  402.   const codes = [];
  403.   codes[0] = "x-mac-roman";
  404.   codes[6] = "x-mac-greek";
  405.   codes[35] = "x-mac-turkish";
  406.   codes[513] = "ISO-8859-1";
  407.   codes[514] = "ISO-8859-2";
  408.   codes[517] = "ISO-8859-5";
  409.   codes[518] = "ISO-8859-6";
  410.   codes[519] = "ISO-8859-7";
  411.   codes[520] = "ISO-8859-8";
  412.   codes[521] = "ISO-8859-9";
  413.   codes[1049] = "IBM864";
  414.   codes[1280] = "windows-1252";
  415.   codes[1281] = "windows-1250";
  416.   codes[1282] = "windows-1251";
  417.   codes[1283] = "windows-1253";
  418.   codes[1284] = "windows-1254";
  419.   codes[1285] = "windows-1255";
  420.   codes[1286] = "windows-1256";
  421.   codes[1536] = "us-ascii";
  422.   codes[1584] = "GB2312";
  423.   codes[1585] = "x-gbk";
  424.   codes[1600] = "EUC-KR";
  425.   codes[2080] = "ISO-2022-JP";
  426.   codes[2096] = "ISO-2022-CN";
  427.   codes[2112] = "ISO-2022-KR";
  428.   codes[2336] = "EUC-JP";
  429.   codes[2352] = "GB2312";
  430.   codes[2353] = "x-euc-tw";
  431.   codes[2368] = "EUC-KR";
  432.   codes[2561] = "Shift_JIS";
  433.   codes[2562] = "KOI8-R";
  434.   codes[2563] = "Big5";
  435.   codes[2565] = "HZ-GB-2312";
  436.  
  437.   if (codes[aCode])
  438.     return codes[aCode];
  439.  
  440.   return getLocalizedPref("intl.charset.default", DEFAULT_QUERY_CHARSET);
  441. }
  442. function fileCharsetFromCode(aCode) {
  443.   const codes = [
  444.     "x-mac-roman",           // 0
  445.     "Shift_JIS",             // 1
  446.     "Big5",                  // 2
  447.     "EUC-KR",                // 3
  448.     "X-MAC-ARABIC",          // 4
  449.     "X-MAC-HEBREW",          // 5
  450.     "X-MAC-GREEK",           // 6
  451.     "X-MAC-CYRILLIC",        // 7
  452.     "X-MAC-DEVANAGARI" ,     // 9
  453.     "X-MAC-GURMUKHI",        // 10
  454.     "X-MAC-GUJARATI",        // 11
  455.     "X-MAC-ORIYA",           // 12
  456.     "X-MAC-BENGALI",         // 13
  457.     "X-MAC-TAMIL",           // 14
  458.     "X-MAC-TELUGU",          // 15
  459.     "X-MAC-KANNADA",         // 16
  460.     "X-MAC-MALAYALAM",       // 17
  461.     "X-MAC-SINHALESE",       // 18
  462.     "X-MAC-BURMESE",         // 19
  463.     "X-MAC-KHMER",           // 20
  464.     "X-MAC-THAI",            // 21
  465.     "X-MAC-LAOTIAN",         // 22
  466.     "X-MAC-GEORGIAN",        // 23
  467.     "X-MAC-ARMENIAN",        // 24
  468.     "GB2312",                // 25
  469.     "X-MAC-TIBETAN",         // 26
  470.     "X-MAC-MONGOLIAN",       // 27
  471.     "X-MAC-ETHIOPIC",        // 28
  472.     "X-MAC-CENTRALEURROMAN", // 29
  473.     "X-MAC-VIETNAMESE",      // 30
  474.     "X-MAC-EXTARABIC"        // 31
  475.   ];
  476.   // Sherlock files have always defaulted to x-mac-roman, so do that here too
  477.   return codes[aCode] || codes[0];
  478. }
  479.  
  480. /**
  481.  * Returns a string interpretation of aBytes using aCharset, or null on
  482.  * failure.
  483.  */
  484. function bytesToString(aBytes, aCharset) {
  485.   var converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].
  486.                   createInstance(Ci.nsIScriptableUnicodeConverter);
  487.   LOG("bytesToString: converting using charset: " + aCharset);
  488.  
  489.   try {
  490.     converter.charset = aCharset;
  491.     return converter.convertFromByteArray(aBytes, aBytes.length);
  492.   } catch (ex) {}
  493.  
  494.   return null;
  495. }
  496.  
  497. /**
  498.  * Converts an array of bytes representing a Sherlock file into an array of
  499.  * lines representing the useful data from the file.
  500.  *
  501.  * @param aBytes
  502.  *        The array of bytes representing the Sherlock file.
  503.  * @param aCharsetCode
  504.  *        An integer value representing a character set code to be passed to
  505.  *        fileCharsetFromCode, or null for the default Sherlock encoding.
  506.  */
  507. function sherlockBytesToLines(aBytes, aCharsetCode) {
  508.   // fileCharsetFromCode returns the default encoding if aCharsetCode is null
  509.   var charset = fileCharsetFromCode(aCharsetCode);
  510.  
  511.   var dataString = bytesToString(aBytes, charset);
  512.   ENSURE(dataString, "sherlockBytesToLines: Couldn't convert byte array!",
  513.          Cr.NS_ERROR_FAILURE);
  514.  
  515.   // Split the string into lines, and filter out comments and
  516.   // whitespace-only lines
  517.   return dataString.split(NEW_LINES).filter(isUsefulLine);
  518. }
  519.  
  520. /**
  521.  * Gets the current value of the locale.  It's possible for this preference to
  522.  * be localized, so we have to do a little extra work here.  Similar code
  523.  * exists in nsHttpHandler.cpp when building the UA string.
  524.  */
  525. function getLocale() {
  526.   const localePref = "general.useragent.locale";
  527.   var locale = getLocalizedPref(localePref);
  528.   if (locale)
  529.     return locale;
  530.  
  531.   // Not localized
  532.   var prefs = Cc["@mozilla.org/preferences-service;1"].
  533.               getService(Ci.nsIPrefBranch);
  534.   return prefs.getCharPref(localePref);
  535. }
  536.  
  537. /**
  538.  * Wrapper for nsIPrefBranch::getComplexValue.
  539.  * @param aPrefName
  540.  *        The name of the pref to get.
  541.  * @returns aDefault if the requested pref doesn't exist.
  542.  */
  543. function getLocalizedPref(aPrefName, aDefault) {
  544.   var prefB = Cc["@mozilla.org/preferences-service;1"].
  545.               getService(Ci.nsIPrefBranch);
  546.   const nsIPLS = Ci.nsIPrefLocalizedString;
  547.   try {
  548.     return prefB.getComplexValue(aPrefName, nsIPLS).data;
  549.   } catch (ex) {}
  550.  
  551.   return aDefault;
  552. }
  553.  
  554. /**
  555.  * Wrapper for nsIPrefBranch::setComplexValue.
  556.  * @param aPrefName
  557.  *        The name of the pref to set.
  558.  */
  559. function setLocalizedPref(aPrefName, aValue) {
  560.   var prefB = Cc["@mozilla.org/preferences-service;1"].
  561.               getService(Ci.nsIPrefBranch);
  562.   const nsIPLS = Ci.nsIPrefLocalizedString;
  563.   try {
  564.     var pls = Components.classes["@mozilla.org/pref-localizedstring;1"]
  565.                         .createInstance(Ci.nsIPrefLocalizedString);
  566.     pls.data = aValue;
  567.     prefB.setComplexValue(aPrefName, nsIPLS, pls);
  568.   } catch (ex) {}
  569. }
  570.  
  571. /**
  572.  * Wrapper for nsIPrefBranch::getBoolPref.
  573.  * @param aPrefName
  574.  *        The name of the pref to get.
  575.  * @returns aDefault if the requested pref doesn't exist.
  576.  */
  577. function getBoolPref(aName, aDefault) {
  578.   var prefB = Cc["@mozilla.org/preferences-service;1"].
  579.               getService(Ci.nsIPrefBranch);
  580.   try {
  581.     return prefB.getBoolPref(aName);
  582.   } catch (ex) {
  583.     return aDefault;
  584.   }
  585. }
  586.  
  587. /**
  588.  * Get a unique nsIFile object with a sanitized name, based on the engine name.
  589.  * @param aName
  590.  *        A name to "sanitize". Can be an empty string, in which case a random
  591.  *        8 character filename will be produced.
  592.  * @returns A nsIFile object in the user's search engines directory with a
  593.  *          unique sanitized name.
  594.  */
  595. function getSanitizedFile(aName) {
  596.   var fileName = sanitizeName(aName) + "." + XML_FILE_EXT;
  597.   var file = getDir(NS_APP_USER_SEARCH_DIR);
  598.   file.append(fileName);
  599.   file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, PERMS_FILE);
  600.   return file;
  601. }
  602.  
  603. /**
  604.  * Removes all characters not in the "chars" string from aName.
  605.  *
  606.  * @returns a sanitized name to be used as a filename, or a random name
  607.  *          if a sanitized name cannot be obtained (if aName contains
  608.  *          no valid characters).
  609.  */
  610. function sanitizeName(aName) {
  611.   const chars = "-abcdefghijklmnopqrstuvwxyz0123456789";
  612.   const maxLength = 60;
  613.  
  614.   var name = aName.toLowerCase();
  615.   name = name.replace(/ /g, "-");
  616.   name = name.split("").filter(function (el) {
  617.                                  return chars.indexOf(el) != -1;
  618.                                }).join("");
  619.  
  620.   if (!name) {
  621.     // Our input had no valid characters - use a random name
  622.     var cl = chars.length - 1;
  623.     for (var i = 0; i < 8; ++i)
  624.       name += chars.charAt(Math.round(Math.random() * cl));
  625.   }
  626.  
  627.   if (name.length > maxLength)
  628.     name = name.substring(0, maxLength);
  629.  
  630.   return name;
  631. }
  632.  
  633. /**
  634.  * Notifies watchers of SEARCH_ENGINE_TOPIC about changes to an engine or to
  635.  * the state of the search service.
  636.  *
  637.  * @param aEngine
  638.  *        The nsISearchEngine object to which the change applies.
  639.  * @param aVerb
  640.  *        A verb describing the change.
  641.  *
  642.  * @see nsIBrowserSearchService.idl
  643.  */
  644. function notifyAction(aEngine, aVerb) {
  645.   var os = Cc["@mozilla.org/observer-service;1"].
  646.            getService(Ci.nsIObserverService);
  647.   LOG("NOTIFY: Engine: \"" + aEngine.name + "\"; Verb: \"" + aVerb + "\"");
  648.   os.notifyObservers(aEngine, SEARCH_ENGINE_TOPIC, aVerb);
  649. }
  650.  
  651. /**
  652.  * Simple object representing a name/value pair.
  653.  */
  654. function QueryParameter(aName, aValue) {
  655.   ENSURE_ARG(aName && (aValue != null),
  656.              "missing name or value for QueryParameter!");
  657.  
  658.   this.name = aName;
  659.   this.value = aValue;
  660. }
  661.  
  662. /**
  663.  * Perform OpenSearch parameter substitution on aParamValue.
  664.  *
  665.  * @param aParamValue
  666.  *        A string containing OpenSearch search parameters.
  667.  * @param aSearchTerms
  668.  *        The user-provided search terms. This string will inserted into
  669.  *        aParamValue as the value of the OS_PARAM_USER_DEFINED parameter.
  670.  *        This value must already be escaped appropriately - it is inserted
  671.  *        as-is.
  672.  * @param aQueryEncoding
  673.  *        The value to use for the OS_PARAM_INPUT_ENCODING parameter. See
  674.  *        definition in the OpenSearch spec.
  675.  *
  676.  * @see http://opensearch.a9.com/spec/1.1/querysyntax/#core
  677.  */
  678. function ParamSubstitution(aParamValue, aSearchTerms, aEngine) {
  679.   var value = aParamValue;
  680.  
  681.   var distributionID = MOZ_DISTRIBUTION_ID;
  682.   try {
  683.     var prefB = Cc["@mozilla.org/preferences-service;1"].
  684.                 getService(Ci.nsIPrefBranch);
  685.     distributionID = prefB.getCharPref(BROWSER_SEARCH_PREF + "distributionID");
  686.   }
  687.   catch (ex) { }
  688.  
  689.   // Custom search parameters. These are only available to default search
  690.   // engines.
  691.   if (aEngine._isDefault) {
  692.     value = value.replace(MOZ_PARAM_LOCALE, getLocale());
  693.     value = value.replace(MOZ_PARAM_DIST_ID, distributionID);
  694.     value = value.replace(MOZ_PARAM_OFFICIAL, MOZ_OFFICIAL);
  695.   }
  696.  
  697.   // Insert the OpenSearch parameters we're confident about
  698.   value = value.replace(OS_PARAM_USER_DEFINED, aSearchTerms);
  699.   value = value.replace(OS_PARAM_INPUT_ENCODING, aEngine.queryCharset);
  700.   value = value.replace(OS_PARAM_LANGUAGE,
  701.                         getLocale() || OS_PARAM_LANGUAGE_DEF);
  702.   value = value.replace(OS_PARAM_OUTPUT_ENCODING,
  703.                         OS_PARAM_OUTPUT_ENCODING_DEF);
  704.  
  705.   // Replace any optional parameters
  706.   value = value.replace(OS_PARAM_OPTIONAL, "");
  707.  
  708.   // Insert any remaining required params with our default values
  709.   for (var i = 0; i < OS_UNSUPPORTED_PARAMS.length; ++i) {
  710.     value = value.replace(OS_UNSUPPORTED_PARAMS[i][0],
  711.                           OS_UNSUPPORTED_PARAMS[i][1]);
  712.   }
  713.  
  714.   return value;
  715. }
  716.  
  717. /**
  718.  * Creates a mozStorage statement that can be used to access the database we
  719.  * use to hold metadata.
  720.  *
  721.  * @param dbconn  the database that the statement applies to
  722.  * @param sql     a string specifying the sql statement that should be created
  723.  */
  724. function createStatement (dbconn, sql) {
  725.   var stmt = dbconn.createStatement(sql);
  726.   var wrapper = Cc["@mozilla.org/storage/statement-wrapper;1"].
  727.                 createInstance(Ci.mozIStorageStatementWrapper);
  728.  
  729.   wrapper.initialize(stmt);
  730.   return wrapper;
  731. }
  732.  
  733. /**
  734.  * Creates an engineURL object, which holds the query URL and all parameters.
  735.  *
  736.  * @param aType
  737.  *        A string containing the name of the MIME type of the search results
  738.  *        returned by this URL.
  739.  * @param aMethod
  740.  *        The HTTP request method. Must be a case insensitive value of either
  741.  *        "GET" or "POST".
  742.  * @param aTemplate
  743.  *        The URL to which search queries should be sent. For GET requests,
  744.  *        must contain the string "{searchTerms}", to indicate where the user
  745.  *        entered search terms should be inserted.
  746.  *
  747.  * @see http://opensearch.a9.com/spec/1.1/querysyntax/#urltag
  748.  *
  749.  * @throws NS_ERROR_NOT_IMPLEMENTED if aType is unsupported.
  750.  */
  751. function EngineURL(aType, aMethod, aTemplate) {
  752.   ENSURE_ARG(aType && aMethod && aTemplate,
  753.              "missing type, method or template for EngineURL!");
  754.  
  755.   var method = aMethod.toUpperCase();
  756.   var type   = aType.toLowerCase();
  757.  
  758.   ENSURE_ARG(method == "GET" || method == "POST",
  759.              "method passed to EngineURL must be \"GET\" or \"POST\"");
  760.  
  761.   this.type     = type;
  762.   this.method   = method;
  763.   this.params   = [];
  764.  
  765.   var templateURI = makeURI(aTemplate);
  766.   ENSURE(templateURI, "new EngineURL: template is not a valid URI!",
  767.          Cr.NS_ERROR_FAILURE);
  768.  
  769.   switch (templateURI.scheme) {
  770.     case "http":
  771.     case "https":
  772.     // Disable these for now, see bug 295018
  773.     // case "file":
  774.     // case "resource":
  775.       this.template = aTemplate;
  776.       break;
  777.     default:
  778.       ENSURE(false, "new EngineURL: template uses invalid scheme!",
  779.              Cr.NS_ERROR_FAILURE);
  780.   }
  781. }
  782. EngineURL.prototype = {
  783.  
  784.   addParam: function SRCH_EURL_addParam(aName, aValue) {
  785.     this.params.push(new QueryParameter(aName, aValue));
  786.   },
  787.  
  788.   getSubmission: function SRCH_EURL_getSubmission(aSearchTerms, aEngine) {
  789.     var url = ParamSubstitution(this.template, aSearchTerms, aEngine);
  790.  
  791.     // Create an application/x-www-form-urlencoded representation of our params
  792.     // (name=value&name=value&name=value)
  793.     var dataString = "";
  794.     for (var i = 0; i < this.params.length; ++i) {
  795.       var param = this.params[i];
  796.       var value = ParamSubstitution(param.value, aSearchTerms, aEngine);
  797.  
  798.       dataString += (i > 0 ? "&" : "") + param.name + "=" + value;
  799.     }
  800.  
  801.     var postData = null;
  802.     if (this.method == "GET") {
  803.       // GET method requests have no post data, and append the encoded
  804.       // query string to the url...
  805.       if (url.indexOf("?") == -1 && dataString)
  806.         url += "?";
  807.       url += dataString;
  808.     } else if (this.method == "POST") {
  809.       // POST method requests must wrap the encoded text in a MIME
  810.       // stream and supply that as POSTDATA.
  811.       var stringStream = Cc["@mozilla.org/io/string-input-stream;1"].
  812.                          createInstance(Ci.nsIStringInputStream);
  813. //@line 876 "e:\fx19rel\WINNT_5.2_Depend\mozilla\browser\components\search\nsSearchService.js"
  814.       stringStream.data = dataString;
  815. //@line 878 "e:\fx19rel\WINNT_5.2_Depend\mozilla\browser\components\search\nsSearchService.js"
  816.  
  817.       postData = Cc["@mozilla.org/network/mime-input-stream;1"].
  818.                  createInstance(Ci.nsIMIMEInputStream);
  819.       postData.addHeader("Content-Type", "application/x-www-form-urlencoded");
  820.       postData.addContentLength = true;
  821.       postData.setData(stringStream);
  822.     }
  823.  
  824.     return new Submission(makeURI(url), postData);
  825.   },
  826.  
  827.   /**
  828.    * Serializes the engine object to a OpenSearch Url element.
  829.    * @param aDoc
  830.    *        The document to use to create the Url element.
  831.    * @param aElement
  832.    *        The element to which the created Url element is appended.
  833.    *
  834.    * @see http://opensearch.a9.com/spec/1.1/querysyntax/#urltag
  835.    */
  836.   _serializeToElement: function SRCH_EURL_serializeToEl(aDoc, aElement) {
  837.     var url = aDoc.createElementNS(OPENSEARCH_NS_11, "Url");
  838.     url.setAttribute("type", this.type);
  839.     url.setAttribute("method", this.method);
  840.     url.setAttribute("template", this.template);
  841.  
  842.     for (var i = 0; i < this.params.length; ++i) {
  843.       var param = aDoc.createElementNS(OPENSEARCH_NS_11, "Param");
  844.       param.setAttribute("name", this.params[i].name);
  845.       param.setAttribute("value", this.params[i].value);
  846.       url.appendChild(aDoc.createTextNode("\n  "));
  847.       url.appendChild(param);
  848.     }
  849.     url.appendChild(aDoc.createTextNode("\n"));
  850.     aElement.appendChild(url);
  851.   }
  852. };
  853.  
  854. /**
  855.  * nsISearchEngine constructor.
  856.  * @param aLocation
  857.  *        A nsILocalFile or nsIURI object representing the location of the
  858.  *        search engine data file.
  859.  * @param aSourceDataType
  860.  *        The data type of the file used to describe the engine. Must be either
  861.  *        DATA_XML or DATA_TEXT.
  862.  * @param aIsReadOnly
  863.  *        Boolean indicating whether the engine should be treated as read-only.
  864.  *        Read only engines cannot be serialized to file.
  865.  */
  866. function Engine(aLocation, aSourceDataType, aIsReadOnly) {
  867.   this._dataType = aSourceDataType;
  868.   this._readOnly = aIsReadOnly;
  869.   this._urls = [];
  870.  
  871.   if (aLocation instanceof Ci.nsILocalFile) {
  872.     // we already have a file (e.g. loading engines from disk)
  873.     this._file = aLocation;
  874.   } else if (aLocation instanceof Ci.nsIURI) {
  875.     this._uri = aLocation;
  876.     switch (aLocation.scheme) {
  877.       case "https":
  878.       case "http":
  879.       case "ftp":
  880.       case "data":
  881.       case "file":
  882.       case "resource":
  883.         this._uri = aLocation;
  884.         break;
  885.       default:
  886.         ERROR("Invalid URI passed to the nsISearchEngine constructor",
  887.               Cr.NS_ERROR_INVALID_ARG);
  888.     }
  889.   } else
  890.     ERROR("Engine location is neither a File nor a URI object",
  891.           Cr.NS_ERROR_INVALID_ARG);
  892. }
  893.  
  894. Engine.prototype = {
  895.   // The engine's alias.
  896.   _alias: null,
  897.   // The data describing the engine. Is either an array of bytes, for Sherlock
  898.   // files, or an XML document element, for XML plugins.
  899.   _data: null,
  900.   // The engine's data type. See data types (DATA_) defined above.
  901.   _dataType: null,
  902.   // Whether or not the engine is readonly.
  903.   _readOnly: true,
  904.   // The engine's description
  905.   _description: "",
  906.   // Used to store the engine to replace, if we're an update to an existing
  907.   // engine.
  908.   _engineToUpdate: null,
  909.   // The file from which the plugin was loaded.
  910.   _file: null,
  911.   // Set to true if the engine has a preferred icon (an icon that should not be
  912.   // overridden by a non-preferred icon).
  913.   _hasPreferredIcon: null,
  914.   // Whether the engine is hidden from the user.
  915.   _hidden: null,
  916.   // The engine's name.
  917.   _name: null,
  918.   // The engine type. See engine types (TYPE_) defined above.
  919.   _type: null,
  920.   // The name of the charset used to submit the search terms.
  921.   _queryCharset: null,
  922.   // A URL string pointing to the engine's search form.
  923.   _searchForm: null,
  924.   // The URI object from which the engine was retrieved.
  925.   // This is null for local plugins, and is used for error messages and logging.
  926.   _uri: null,
  927.   // Whether to obtain user confirmation before adding the engine. This is only
  928.   // used when the engine is first added to the list.
  929.   _confirm: false,
  930.   // Whether to set this as the current engine as soon as it is loaded.  This
  931.   // is only used when the engine is first added to the list.
  932.   _useNow: true,
  933.   // Where the engine was loaded from. Can be one of: SEARCH_APP_DIR,
  934.   // SEARCH_PROFILE_DIR, SEARCH_IN_EXTENSION.
  935.   __installLocation: null,
  936.   // The number of days between update checks for new versions
  937.   _updateInterval: null,
  938.   // The url to check at for a new update
  939.   _updateURL: null,
  940.   // The url to check for a new icon
  941.   _iconUpdateURL: null,
  942.   // A reference to the timer used for lazily serializing the engine to file
  943.   _serializeTimer: null,
  944.  
  945.   /**
  946.    * Retrieves the data from the engine's file. If the engine's dataType is
  947.    * XML, the document element is placed in the engine's data field. For text
  948.    * engines, the data is just read directly from file and placed as an array
  949.    * of lines in the engine's data field.
  950.    */
  951.   _initFromFile: function SRCH_ENG_initFromFile() {
  952.     ENSURE(this._file && this._file.exists(),
  953.            "File must exist before calling initFromFile!",
  954.            Cr.NS_ERROR_UNEXPECTED);
  955.  
  956.     var fileInStream = Cc["@mozilla.org/network/file-input-stream;1"].
  957.                        createInstance(Ci.nsIFileInputStream);
  958.  
  959.     fileInStream.init(this._file, MODE_RDONLY, PERMS_FILE, false);
  960.  
  961.     switch (this._dataType) {
  962.       case SEARCH_DATA_XML:
  963.         var domParser = Cc["@mozilla.org/xmlextras/domparser;1"].
  964.                         createInstance(Ci.nsIDOMParser);
  965.         var doc = domParser.parseFromStream(fileInStream, "UTF-8",
  966.                                             this._file.fileSize,
  967.                                             "text/xml");
  968.  
  969.         this._data = doc.documentElement;
  970.         break;
  971.       case SEARCH_DATA_TEXT:
  972.         var binaryInStream = Cc["@mozilla.org/binaryinputstream;1"].
  973.                              createInstance(Ci.nsIBinaryInputStream);
  974.         binaryInStream.setInputStream(fileInStream);
  975.  
  976.         var bytes = binaryInStream.readByteArray(binaryInStream.available());
  977.         this._data = bytes;
  978.  
  979.         break;
  980.       default:
  981.         ERROR("Bogus engine _dataType: \"" + this._dataType + "\"",
  982.               Cr.NS_ERROR_UNEXPECTED);
  983.     }
  984.     fileInStream.close();
  985.  
  986.     // Now that the data is loaded, initialize the engine object
  987.     this._initFromData();
  988.   },
  989.  
  990.   /**
  991.    * Retrieves the engine data from a URI.
  992.    */
  993.   _initFromURI: function SRCH_ENG_initFromURI() {
  994.     ENSURE_WARN(this._uri instanceof Ci.nsIURI,
  995.                 "Must have URI when calling _initFromURI!",
  996.                 Cr.NS_ERROR_UNEXPECTED);
  997.  
  998.     LOG("_initFromURI: Downloading engine from: \"" + this._uri.spec + "\".");
  999.  
  1000.     var ios = Cc["@mozilla.org/network/io-service;1"].
  1001.               getService(Ci.nsIIOService);
  1002.     var chan = ios.newChannelFromURI(this._uri);
  1003.  
  1004.     if (this._engineToUpdate && (chan instanceof Ci.nsIHttpChannel)) {
  1005.       var lastModified = engineMetadataService.getAttr(this._engineToUpdate,
  1006.                                                        "updatelastmodified");
  1007.       if (lastModified)
  1008.         chan.setRequestHeader("If-Modified-Since", lastModified, false);
  1009.     }
  1010.     var listener = new loadListener(chan, this, this._onLoad);
  1011.     chan.notificationCallbacks = listener;
  1012.     chan.asyncOpen(listener, null);
  1013.   },
  1014.  
  1015.   /**
  1016.    * Attempts to find an EngineURL object in the set of EngineURLs for
  1017.    * this Engine that has the given type string.  (This corresponds to the
  1018.    * "type" attribute in the "Url" node in the OpenSearch spec.)
  1019.    * This method will return the first matching URL object found, or null
  1020.    * if no matching URL is found.
  1021.    *
  1022.    * @param aType string to match the EngineURL's type attribute
  1023.    */
  1024.   _getURLOfType: function SRCH_ENG__getURLOfType(aType) {
  1025.     for (var i = 0; i < this._urls.length; ++i) {
  1026.       if (this._urls[i].type == aType)
  1027.         return this._urls[i];
  1028.     }
  1029.  
  1030.     return null;
  1031.   },
  1032.  
  1033.   _confirmAddEngine: function SRCH_SVC_confirmAddEngine() {
  1034.     var sbs = Cc["@mozilla.org/intl/stringbundle;1"].
  1035.               getService(Ci.nsIStringBundleService);
  1036.     var stringBundle = sbs.createBundle(SEARCH_BUNDLE);
  1037.     var titleMessage = stringBundle.GetStringFromName("addEngineConfirmTitle");
  1038.  
  1039.     // Display only the hostname portion of the URL.
  1040.     var dialogMessage =
  1041.         stringBundle.formatStringFromName("addEngineConfirmation",
  1042.                                           [this._name, this._uri.host], 2);
  1043.     var checkboxMessage = stringBundle.GetStringFromName("addEngineUseNowText");
  1044.     var addButtonLabel =
  1045.         stringBundle.GetStringFromName("addEngineAddButtonLabel");
  1046.  
  1047.     var ps = Cc["@mozilla.org/embedcomp/prompt-service;1"].
  1048.              getService(Ci.nsIPromptService);
  1049.     var buttonFlags = (ps.BUTTON_TITLE_IS_STRING * ps.BUTTON_POS_0) +
  1050.                       (ps.BUTTON_TITLE_CANCEL    * ps.BUTTON_POS_1) +
  1051.                        ps.BUTTON_POS_0_DEFAULT;
  1052.  
  1053.     var checked = {value: false};
  1054.     // confirmEx returns the index of the button that was pressed.  Since "Add"
  1055.     // is button 0, we want to return the negation of that value.
  1056.     var confirm = !ps.confirmEx(null,
  1057.                                 titleMessage,
  1058.                                 dialogMessage,
  1059.                                 buttonFlags,
  1060.                                 addButtonLabel,
  1061.                                 null, null, // button 1 & 2 names not used
  1062.                                 checkboxMessage,
  1063.                                 checked);
  1064.  
  1065.     return {confirmed: confirm, useNow: checked.value};
  1066.   },
  1067.  
  1068.   /**
  1069.    * Handle the successful download of an engine. Initializes the engine and
  1070.    * triggers parsing of the data. The engine is then flushed to disk. Notifies
  1071.    * the search service once initialization is complete.
  1072.    */
  1073.   _onLoad: function SRCH_ENG_onLoad(aBytes, aEngine) {
  1074.     /**
  1075.      * Handle an error during the load of an engine by prompting the user to
  1076.      * notify him that the load failed.
  1077.      */
  1078.     function onError(aErrorString, aTitleString) {
  1079.       if (aEngine._engineToUpdate) {
  1080.         // We're in an update, so just fail quietly
  1081.         LOG("updating " + aEngine._engineToUpdate.name + " failed");
  1082.         return;
  1083.       }
  1084.       var sbs = Cc["@mozilla.org/intl/stringbundle;1"].
  1085.                 getService(Ci.nsIStringBundleService);
  1086.  
  1087.       var brandBundle = sbs.createBundle(BRAND_BUNDLE);
  1088.       var brandName = brandBundle.GetStringFromName("brandShortName");
  1089.  
  1090.       var searchBundle = sbs.createBundle(SEARCH_BUNDLE);
  1091.       var msgStringName = aErrorString || "error_loading_engine_msg2";
  1092.       var titleStringName = aTitleString || "error_loading_engine_title";
  1093.       var title = searchBundle.GetStringFromName(titleStringName);
  1094.       var text = searchBundle.formatStringFromName(msgStringName,
  1095.                                                    [brandName, aEngine._location],
  1096.                                                    2);
  1097.  
  1098.       var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  1099.                getService(Ci.nsIWindowWatcher);
  1100.       ww.getNewPrompter(null).alert(title, text);
  1101.     }
  1102.  
  1103.     if (!aBytes) {
  1104.       onError();
  1105.       return;
  1106.     }
  1107.  
  1108.     var engineToUpdate = null;
  1109.     if (aEngine._engineToUpdate) {
  1110.       engineToUpdate = aEngine._engineToUpdate.wrappedJSObject;
  1111.  
  1112.       // Make this new engine use the old engine's file.
  1113.       aEngine._file = engineToUpdate._file;
  1114.     }
  1115.  
  1116.     switch (aEngine._dataType) {
  1117.       case SEARCH_DATA_XML:
  1118.         var parser = Cc["@mozilla.org/xmlextras/domparser;1"].
  1119.                      createInstance(Ci.nsIDOMParser);
  1120.         var doc = parser.parseFromBuffer(aBytes, aBytes.length, "text/xml");
  1121.         aEngine._data = doc.documentElement;
  1122.         break;
  1123.       case SEARCH_DATA_TEXT:
  1124.         aEngine._data = aBytes;
  1125.         break;
  1126.       default:
  1127.         onError();
  1128.         LOG("_onLoad: Bogus engine _dataType: \"" + this._dataType + "\"");
  1129.         return;
  1130.     }
  1131.  
  1132.     try {
  1133.       // Initialize the engine from the obtained data
  1134.       aEngine._initFromData();
  1135.     } catch (ex) {
  1136.       LOG("_onLoad: Failed to init engine!\n" + ex);
  1137.       // Report an error to the user
  1138.       onError();
  1139.       return;
  1140.     }
  1141.  
  1142.     // Check to see if this is a duplicate engine. If we're confirming the
  1143.     // engine load, then we display a "this is a duplicate engine" prompt,
  1144.     // otherwise we fail silently.
  1145.     if (!engineToUpdate) {
  1146.       var ss = Cc["@mozilla.org/browser/search-service;1"].
  1147.                getService(Ci.nsIBrowserSearchService);
  1148.       if (ss.getEngineByName(aEngine.name)) {
  1149.         if (aEngine._confirm)
  1150.           onError("error_duplicate_engine_msg", "error_invalid_engine_title");
  1151.  
  1152.         LOG("_onLoad: duplicate engine found, bailing");
  1153.         return;
  1154.       }
  1155.     }
  1156.  
  1157.     // If requested, confirm the addition now that we have the title.
  1158.     // This property is only ever true for engines added via
  1159.     // nsIBrowserSearchService::addEngine.
  1160.     if (aEngine._confirm) {
  1161.       var confirmation = aEngine._confirmAddEngine();
  1162.       LOG("_onLoad: confirm is " + confirmation.confirmed +
  1163.           "; useNow is " + confirmation.useNow);
  1164.       if (!confirmation.confirmed)
  1165.         return;
  1166.       aEngine._useNow = confirmation.useNow;
  1167.     }
  1168.  
  1169.     // If we don't yet have a file, get one now. The only case where we would
  1170.     // already have a file is if this is an update and _file was set above.
  1171.     if (!aEngine._file)
  1172.       aEngine._file = getSanitizedFile(aEngine.name);
  1173.  
  1174.     if (engineToUpdate) {
  1175.       // Keep track of the last modified date, so that we can make conditional
  1176.       // requests for future updates.
  1177.       engineMetadataService.setAttr(aEngine, "updatelastmodified",
  1178.                                     (new Date()).toUTCString());
  1179.  
  1180.       // Set the new engine's icon, if it doesn't yet have one.
  1181.       if (!aEngine._iconURI && engineToUpdate._iconURI)
  1182.         aEngine._iconURI = engineToUpdate._iconURI;
  1183.  
  1184.       // Clear the "use now" flag since we don't want to be changing the
  1185.       // current engine for an update.
  1186.       aEngine._useNow = false;
  1187.     }
  1188.  
  1189.     // Write the engine to file
  1190.     aEngine._serializeToFile();
  1191.  
  1192.     // Notify the search service of the sucessful load. It will deal with
  1193.     // updates by checking aEngine._engineToUpdate.
  1194.     notifyAction(aEngine, SEARCH_ENGINE_LOADED);
  1195.   },
  1196.  
  1197.   /**
  1198.    * Sets the .iconURI property of the engine.
  1199.    *
  1200.    *  @param aIconURL
  1201.    *         A URI string pointing to the engine's icon. Must have a http[s],
  1202.    *         ftp, or data scheme. Icons with HTTP[S] or FTP schemes will be
  1203.    *         downloaded and converted to data URIs for storage in the engine
  1204.    *         XML files, if the engine is not readonly.
  1205.    *  @param aIsPreferred
  1206.    *         Whether or not this icon is to be preferred. Preferred icons can
  1207.    *         override non-preferred icons.
  1208.    */
  1209.   _setIcon: function SRCH_ENG_setIcon(aIconURL, aIsPreferred) {
  1210.     // If we already have a preferred icon, and this isn't a preferred icon,
  1211.     // just ignore it.
  1212.     if (this._hasPreferredIcon && !aIsPreferred)
  1213.       return;
  1214.  
  1215.     var uri = makeURI(aIconURL);
  1216.  
  1217.     // Ignore bad URIs
  1218.     if (!uri)
  1219.       return;
  1220.  
  1221.     LOG("_setIcon: Setting icon url \"" + uri.spec + "\" for engine \""
  1222.         + this.name + "\".");
  1223.     // Only accept remote icons from http[s] or ftp
  1224.     switch (uri.scheme) {
  1225.       case "data":
  1226.         this._iconURI = uri;
  1227.         notifyAction(this, SEARCH_ENGINE_CHANGED);
  1228.         this._hasPreferredIcon = aIsPreferred;
  1229.         break;
  1230.       case "http":
  1231.       case "https":
  1232.       case "ftp":
  1233.         // No use downloading the icon if the engine file is read-only
  1234.         if (!this._readOnly) {
  1235.           LOG("_setIcon: Downloading icon: \"" + uri.spec +
  1236.               "\" for engine: \"" + this.name + "\"");
  1237.           var ios = Cc["@mozilla.org/network/io-service;1"].
  1238.                     getService(Ci.nsIIOService);
  1239.           var chan = ios.newChannelFromURI(uri);
  1240.  
  1241.           function iconLoadCallback(aByteArray, aEngine) {
  1242.             // This callback may run after we've already set a preferred icon,
  1243.             // so check again.
  1244.             if (aEngine._hasPreferredIcon && !aIsPreferred)
  1245.               return;
  1246.  
  1247.             if (!aByteArray || aByteArray.length > MAX_ICON_SIZE) {
  1248.               LOG("iconLoadCallback: load failed, or the icon was too large!");
  1249.               return;
  1250.             }
  1251.  
  1252.             var str = btoa(String.fromCharCode.apply(null, aByteArray));
  1253.             aEngine._iconURI = makeURI(ICON_DATAURL_PREFIX + str);
  1254.  
  1255.             // The engine might not have a file yet, if it's being downloaded,
  1256.             // because the request for the engine file itself (_onLoad) may not
  1257.             // yet be complete. In that case, this change will be written to
  1258.             // file when _onLoad is called.
  1259.             if (aEngine._file)
  1260.               aEngine._serializeToFile();
  1261.  
  1262.             notifyAction(aEngine, SEARCH_ENGINE_CHANGED);
  1263.             aEngine._hasPreferredIcon = aIsPreferred;
  1264.           }
  1265.  
  1266.           // If we're currently acting as an "update engine", then the callback
  1267.           // should set the icon on the engine we're updating and not us, since
  1268.           // |this| might be gone by the time the callback runs.
  1269.           var engineToSet = this._engineToUpdate || this;
  1270.  
  1271.           var listener = new loadListener(chan, engineToSet, iconLoadCallback);
  1272.           chan.notificationCallbacks = listener;
  1273.           chan.asyncOpen(listener, null);
  1274.         }
  1275.         break;
  1276.     }
  1277.   },
  1278.  
  1279.   /**
  1280.    * Initialize this Engine object from the collected data.
  1281.    */
  1282.   _initFromData: function SRCH_ENG_initFromData() {
  1283.  
  1284.     ENSURE_WARN(this._data, "Can't init an engine with no data!",
  1285.                 Cr.NS_ERROR_UNEXPECTED);
  1286.  
  1287.     // Find out what type of engine we are
  1288.     switch (this._dataType) {
  1289.       case SEARCH_DATA_XML:
  1290.         if (checkNameSpace(this._data, [MOZSEARCH_LOCALNAME],
  1291.             [MOZSEARCH_NS_10])) {
  1292.  
  1293.           LOG("_init: Initing MozSearch plugin from " + this._location);
  1294.  
  1295.           this._type = SEARCH_TYPE_MOZSEARCH;
  1296.           this._parseAsMozSearch();
  1297.  
  1298.         } else if (checkNameSpace(this._data, [OPENSEARCH_LOCALNAME],
  1299.                                   OPENSEARCH_NAMESPACES)) {
  1300.  
  1301.           LOG("_init: Initing OpenSearch plugin from " + this._location);
  1302.  
  1303.           this._type = SEARCH_TYPE_OPENSEARCH;
  1304.           this._parseAsOpenSearch();
  1305.  
  1306.         } else
  1307.           ENSURE(false, this._location + " is not a valid search plugin.",
  1308.                  Cr.NS_ERROR_FAILURE);
  1309.  
  1310.         break;
  1311.       case SEARCH_DATA_TEXT:
  1312.         LOG("_init: Initing Sherlock plugin from " + this._location);
  1313.  
  1314.         // the only text-based format we support is Sherlock
  1315.         this._type = SEARCH_TYPE_SHERLOCK;
  1316.         this._parseAsSherlock();
  1317.     }
  1318.  
  1319.     // No need to keep a ref to our data (which in some cases can be a document
  1320.     // element) past this point
  1321.     this._data = null;
  1322.   },
  1323.  
  1324.   /**
  1325.    * Initialize this Engine object from a collection of metadata.
  1326.    */
  1327.   _initFromMetadata: function SRCH_ENG_initMetaData(aName, aIconURL, aAlias,
  1328.                                                     aDescription, aMethod,
  1329.                                                     aTemplate) {
  1330.     ENSURE_WARN(!this._readOnly,
  1331.                 "Can't call _initFromMetaData on a readonly engine!",
  1332.                 Cr.NS_ERROR_FAILURE);
  1333.  
  1334.     this._urls.push(new EngineURL("text/html", aMethod, aTemplate));
  1335.  
  1336.     this._name = aName;
  1337.     this.alias = aAlias;
  1338.     this._description = aDescription;
  1339.     this._setIcon(aIconURL, true);
  1340.  
  1341.     this._serializeToFile();
  1342.   },
  1343.  
  1344.   /**
  1345.    * Extracts data from an OpenSearch URL element and creates an EngineURL
  1346.    * object which is then added to the engine's list of URLs.
  1347.    *
  1348.    * @throws NS_ERROR_FAILURE if a URL object could not be created.
  1349.    *
  1350.    * @see http://opensearch.a9.com/spec/1.1/querysyntax/#urltag.
  1351.    * @see EngineURL()
  1352.    */
  1353.   _parseURL: function SRCH_ENG_parseURL(aElement) {
  1354.     var type     = aElement.getAttribute("type");
  1355.     // According to the spec, method is optional, defaulting to "GET" if not
  1356.     // specified
  1357.     var method   = aElement.getAttribute("method") || "GET";
  1358.     var template = aElement.getAttribute("template");
  1359.  
  1360.     try {
  1361.       var url = new EngineURL(type, method, template);
  1362.     } catch (ex) {
  1363.       LOG("_parseURL: failed to add " + template + " as a URL");
  1364.       throw Cr.NS_ERROR_FAILURE;
  1365.     }
  1366.  
  1367.     for (var i = 0; i < aElement.childNodes.length; ++i) {
  1368.       var param = aElement.childNodes[i];
  1369.       if (param.localName == "Param") {
  1370.         try {
  1371.           url.addParam(param.getAttribute("name"), param.getAttribute("value"));
  1372.         } catch (ex) {
  1373.           // Ignore failure
  1374.           LOG("_parseURL: Url element has an invalid param");
  1375.         }
  1376.       } else if (param.localName == "MozParam" &&
  1377.                  // We only support MozParams for default search engines
  1378.                  this._isDefault) {
  1379.         var value;
  1380.         switch (param.getAttribute("condition")) {
  1381.           case "defaultEngine":
  1382.             const defPref = BROWSER_SEARCH_PREF + "defaultenginename";
  1383.             var defaultPrefB = Cc["@mozilla.org/preferences-service;1"].
  1384.                                getService(Ci.nsIPrefService).
  1385.                                getDefaultBranch(null);
  1386.             const nsIPLS = Ci.nsIPrefLocalizedString;
  1387.             var defaultName;
  1388.             try {
  1389.               defaultName = defaultPrefB.getComplexValue(defPref, nsIPLS).data;
  1390.             } catch (ex) {}
  1391.  
  1392.             // If this engine was the default search engine, use the true value
  1393.             if (this.name == defaultName)
  1394.               value = param.getAttribute("trueValue");
  1395.             else
  1396.               value = param.getAttribute("falseValue");
  1397.             url.addParam(param.getAttribute("name"), value);
  1398.             break;
  1399.  
  1400.           case "pref":
  1401.             try {
  1402.               var prefB = Cc["@mozilla.org/preferences-service;1"].
  1403.                           getService(Ci.nsIPrefBranch);
  1404.               value = prefB.getCharPref(BROWSER_SEARCH_PREF + "param." +
  1405.                                         param.getAttribute("pref"));
  1406.               url.addParam(param.getAttribute("name"), value);
  1407.             } catch (e) { }
  1408.             break;
  1409.         }
  1410.       }
  1411.     }
  1412.  
  1413.     this._urls.push(url);
  1414.   },
  1415.  
  1416.   /**
  1417.    * Get the icon from an OpenSearch Image element.
  1418.    * @see http://opensearch.a9.com/spec/1.1/description/#image
  1419.    */
  1420.   _parseImage: function SRCH_ENG_parseImage(aElement) {
  1421.     LOG("_parseImage: Image textContent: \"" + aElement.textContent + "\"");
  1422.     if (aElement.getAttribute("width")  == "16" &&
  1423.         aElement.getAttribute("height") == "16") {
  1424.       this._setIcon(aElement.textContent, true);
  1425.     }
  1426.   },
  1427.  
  1428.   _parseAsMozSearch: function SRCH_ENG_parseAsMoz() {
  1429.     //forward to the OpenSearch parser
  1430.     this._parseAsOpenSearch();
  1431.   },
  1432.  
  1433.   /**
  1434.    * Extract search engine information from the collected data to initialize
  1435.    * the engine object.
  1436.    */
  1437.   _parseAsOpenSearch: function SRCH_ENG_parseAsOS() {
  1438.     var doc = this._data;
  1439.  
  1440.     // The OpenSearch spec sets a default value for the input encoding.
  1441.     this._queryCharset = OS_PARAM_INPUT_ENCODING_DEF;
  1442.  
  1443.     for (var i = 0; i < doc.childNodes.length; ++i) {
  1444.       var child = doc.childNodes[i];
  1445.       switch (child.localName) {
  1446.         case "ShortName":
  1447.           this._name = child.textContent;
  1448.           break;
  1449.         case "Description":
  1450.           this._description = child.textContent;
  1451.           break;
  1452.         case "Url":
  1453.           try {
  1454.             this._parseURL(child);
  1455.           } catch (ex) {
  1456.             // Parsing of the element failed, just skip it.
  1457.           }
  1458.           break;
  1459.         case "Image":
  1460.           this._parseImage(child);
  1461.           break;
  1462.         case "InputEncoding":
  1463.           this._queryCharset = child.textContent.toUpperCase();
  1464.           break;
  1465.  
  1466.         // Non-OpenSearch elements
  1467.         case "SearchForm":
  1468.           this._searchForm = child.textContent;
  1469.           break;
  1470.         case "UpdateUrl":
  1471.           this._updateURL = child.textContent;
  1472.           break;
  1473.         case "UpdateInterval":
  1474.           this._updateInterval = parseInt(child.textContent);
  1475.           break;
  1476.         case "IconUpdateUrl":
  1477.           this._iconUpdateURL = child.textContent;
  1478.           break;
  1479.       }
  1480.     }
  1481.     ENSURE(this.name && (this._urls.length > 0),
  1482.            "_parseAsOpenSearch: No name, or missing URL!",
  1483.            Cr.NS_ERROR_FAILURE);
  1484.     ENSURE(this.supportsResponseType(URLTYPE_SEARCH_HTML),
  1485.            "_parseAsOpenSearch: No text/html result type!",
  1486.            Cr.NS_ERROR_FAILURE);
  1487.   },
  1488.  
  1489.   /**
  1490.    * Extract search engine information from the collected data to initialize
  1491.    * the engine object.
  1492.    */
  1493.   _parseAsSherlock: function SRCH_ENG_parseAsSherlock() {
  1494.     /**
  1495.      * Trims leading and trailing whitespace from aStr.
  1496.      */
  1497.     function sTrim(aStr) {
  1498.       return aStr.replace(/^\s+/g, "").replace(/\s+$/g, "");
  1499.     }
  1500.  
  1501.     /**
  1502.      * Extracts one Sherlock "section" from aSource. A section is essentially
  1503.      * an HTML element with attributes, but each attribute must be on a new
  1504.      * line, by definition.
  1505.      *
  1506.      * @param aLines
  1507.      *        An array of lines from the sherlock file.
  1508.      * @param aSection
  1509.      *        The name of the section (e.g. "search" or "browser"). This value
  1510.      *        is not case sensitive.
  1511.      * @returns an object whose properties correspond to the section's
  1512.      *          attributes.
  1513.      */
  1514.     function getSection(aLines, aSection) {
  1515.       LOG("_parseAsSherlock::getSection: Sherlock lines:\n" +
  1516.           aLines.join("\n"));
  1517.       var lines = aLines;
  1518.       var startMark = new RegExp("^\\s*<" + aSection.toLowerCase() + "\\s*",
  1519.                                  "gi");
  1520.       var endMark   = /\s*>\s*$/gi;
  1521.  
  1522.       var foundStart = false;
  1523.       var startLine, numberOfLines;
  1524.       // Find the beginning and end of the section
  1525.       for (var i = 0; i < lines.length; i++) {
  1526.         if (foundStart) {
  1527.           if (endMark.test(lines[i])) {
  1528.             numberOfLines = i - startLine;
  1529.             // Remove the end marker
  1530.             lines[i] = lines[i].replace(endMark, "");
  1531.             // If the endmarker was not the only thing on the line, include
  1532.             // this line in the results
  1533.             if (lines[i])
  1534.               numberOfLines++;
  1535.             break;
  1536.           }
  1537.         } else {
  1538.           if (startMark.test(lines[i])) {
  1539.             foundStart = true;
  1540.             // Remove the start marker
  1541.             lines[i] = lines[i].replace(startMark, "");
  1542.             startLine = i;
  1543.             // If the line is empty, don't include it in the result
  1544.             if (!lines[i])
  1545.               startLine++;
  1546.           }
  1547.         }
  1548.       }
  1549.       LOG("_parseAsSherlock::getSection: Start index: " + startLine +
  1550.           "\nNumber of lines: " + numberOfLines);
  1551.       lines = lines.splice(startLine, numberOfLines);
  1552.       LOG("_parseAsSherlock::getSection: Section lines:\n" +
  1553.           lines.join("\n"));
  1554.  
  1555.       var section = {};
  1556.       for (var i = 0; i < lines.length; i++) {
  1557.         var line = sTrim(lines[i]);
  1558.  
  1559.         var els = line.split("=");
  1560.         var name = sTrim(els.shift().toLowerCase());
  1561.         var value = sTrim(els.join("="));
  1562.  
  1563.         if (!name || !value)
  1564.           continue;
  1565.  
  1566.         // Strip leading and trailing whitespace, remove quotes from the
  1567.         // value, and remove any trailing slashes or ">" characters
  1568.         value = value.replace(/^["']/, "")
  1569.                      .replace(/["']\s*[\\\/]?>?\s*$/, "") || "";
  1570.         value = sTrim(value);
  1571.  
  1572.         // Don't clobber existing attributes
  1573.         if (!(name in section))
  1574.           section[name] = value;
  1575.       }
  1576.       return section;
  1577.     }
  1578.  
  1579.     /**
  1580.      * Returns an array of name-value pair arrays representing the Sherlock
  1581.      * file's input elements. User defined inputs return USER_DEFINED
  1582.      * as the value. Elements are returned in the order they appear in the
  1583.      * source file.
  1584.      *
  1585.      *   Example:
  1586.      *      <input name="foo" value="bar">
  1587.      *      <input name="foopy" user>
  1588.      *   Returns:
  1589.      *      [["foo", "bar"], ["foopy", "{searchTerms}"]]
  1590.      *
  1591.      * @param aLines
  1592.      *        An array of lines from the source file.
  1593.      */
  1594.     function getInputs(aLines) {
  1595.  
  1596.       /**
  1597.        * Extracts an attribute value from a given a line of text.
  1598.        *    Example: <input value="foo" name="bar">
  1599.        *      Extracts the string |foo| or |bar| given an input aAttr of
  1600.        *      |value| or |name|.
  1601.        * Attributes may be quoted or unquoted. If unquoted, any whitespace
  1602.        * indicates the end of the attribute value.
  1603.        *    Example: < value=22 33 name=44\334 >
  1604.        *      Returns |22| for "value" and |44\334| for "name".
  1605.        *
  1606.        * @param aAttr
  1607.        *        The name of the attribute for which to obtain the value. This
  1608.        *        value is not case sensitive.
  1609.        * @param aLine
  1610.        *        The line containing the attribute.
  1611.        *
  1612.        * @returns the attribute value, or an empty string if the attribute
  1613.        *          doesn't exist.
  1614.        */
  1615.       function getAttr(aAttr, aLine) {
  1616.         // Used to determine whether an "input" line from a Sherlock file is a
  1617.         // "user defined" input.
  1618.         const userInput = /(\s|["'=])user(\s|[>="'\/\\+]|$)/i;
  1619.  
  1620.         LOG("_parseAsSherlock::getAttr: Getting attr: \"" +
  1621.             aAttr + "\" for line: \"" + aLine + "\"");
  1622.         // We're not case sensitive, but we want to return the attribute value
  1623.         // in its original case, so create a copy of the source
  1624.         var lLine = aLine.toLowerCase();
  1625.         var attr = aAttr.toLowerCase();
  1626.  
  1627.         var attrStart = lLine.search(new RegExp("\\s" + attr, "i"));
  1628.         if (attrStart == -1) {
  1629.  
  1630.           // If this is the "user defined input" (i.e. contains the empty
  1631.           // "user" attribute), return our special keyword
  1632.           if (userInput.test(lLine) && attr == "value") {
  1633.             LOG("_parseAsSherlock::getAttr: Found user input!\nLine:\"" + lLine
  1634.                 + "\"");
  1635.             return USER_DEFINED;
  1636.           }
  1637.           // The attribute doesn't exist - ignore
  1638.           LOG("_parseAsSherlock::getAttr: Failed to find attribute:\nLine:\""
  1639.               + lLine + "\"\nAttr:\"" + attr + "\"");
  1640.           return "";
  1641.         }
  1642.  
  1643.         var valueStart = lLine.indexOf("=", attrStart) + "=".length;
  1644.         if (valueStart == -1)
  1645.           return "";
  1646.  
  1647.         var quoteStart = lLine.indexOf("\"", valueStart);
  1648.         if (quoteStart == -1) {
  1649.  
  1650.           // Unquoted attribute, get the rest of the line, trimmed at the first
  1651.           // sign of whitespace. If the rest of the line is only whitespace,
  1652.           // returns a blank string.
  1653.           return lLine.substr(valueStart).replace(/\s.*$/, "");
  1654.  
  1655.         } else {
  1656.           // Make sure that there's only whitespace between the start of the
  1657.           // value and the first quote. If there is, end the attribute value at
  1658.           // the first sign of whitespace. This prevents us from falling into
  1659.           // the next attribute if this is an unquoted attribute followed by a
  1660.           // quoted attribute.
  1661.           var betweenEqualAndQuote = lLine.substring(valueStart, quoteStart);
  1662.           if (/\S/.test(betweenEqualAndQuote))
  1663.             return lLine.substr(valueStart).replace(/\s.*$/, "");
  1664.  
  1665.           // Adjust the start index to account for the opening quote
  1666.           valueStart = quoteStart + "\"".length;
  1667.           // Find the closing quote
  1668.           valueEnd = lLine.indexOf("\"", valueStart);
  1669.           // If there is no closing quote, just go to the end of the line
  1670.           if (valueEnd == -1)
  1671.             valueEnd = aLine.length;
  1672.         }
  1673.         return aLine.substring(valueStart, valueEnd);
  1674.       }
  1675.  
  1676.       var inputs = [];
  1677.  
  1678.       LOG("_parseAsSherlock::getInputs: Lines:\n" + aLines);
  1679.       // Filter out everything but non-inputs
  1680.       lines = aLines.filter(function (line) {
  1681.         return /^\s*<input/i.test(line);
  1682.       });
  1683.       LOG("_parseAsSherlock::getInputs: Filtered lines:\n" + lines);
  1684.  
  1685.       lines.forEach(function (line) {
  1686.         // Strip leading/trailing whitespace and remove the surrounding markup
  1687.         // ("<input" and ">")
  1688.         line = sTrim(line).replace(/^<input/i, "").replace(/>$/, "");
  1689.  
  1690.         // If this is one of the "directional" inputs (<inputnext>/<inputprev>)
  1691.         const directionalInput = /^(prev|next)/i;
  1692.         if (directionalInput.test(line)) {
  1693.  
  1694.           // Make it look like a normal input by removing "prev" or "next"
  1695.           line = line.replace(directionalInput, "");
  1696.  
  1697.           // If it has a name, give it a dummy value to match previous
  1698.           // nsInternetSearchService behavior
  1699.           if (/name\s*=/i.test(line)) {
  1700.             line += " value=\"0\"";
  1701.           } else
  1702.             return; // Line has no name, skip it
  1703.         }
  1704.  
  1705.         var attrName = getAttr("name", line);
  1706.         var attrValue = getAttr("value", line);
  1707.         LOG("_parseAsSherlock::getInputs: Got input:\nName:\"" + attrName +
  1708.             "\"\nValue:\"" + attrValue + "\"");
  1709.         if (attrValue)
  1710.           inputs.push([attrName, attrValue]);
  1711.       });
  1712.       return inputs;
  1713.     }
  1714.  
  1715.     function err(aErr) {
  1716.       LOG("_parseAsSherlock::err: Sherlock param error:\n" + aErr);
  1717.       throw Cr.NS_ERROR_FAILURE;
  1718.     }
  1719.  
  1720.     // First try converting our byte array using the default Sherlock encoding.
  1721.     // If this fails, or if we find a sourceTextEncoding attribute, we need to
  1722.     // reconvert the byte array using the specified encoding.
  1723.     var sherlockLines, searchSection, sourceTextEncoding, browserSection;
  1724.     try {
  1725.       sherlockLines = sherlockBytesToLines(this._data);
  1726.       searchSection = getSection(sherlockLines, "search");
  1727.       browserSection = getSection(sherlockLines, "browser");
  1728.       sourceTextEncoding = parseInt(searchSection["sourcetextencoding"]);
  1729.       if (sourceTextEncoding) {
  1730.         // Re-convert the bytes using the found sourceTextEncoding
  1731.         sherlockLines = sherlockBytesToLines(this._data, sourceTextEncoding);
  1732.         searchSection = getSection(sherlockLines, "search");
  1733.         browserSection = getSection(sherlockLines, "browser");
  1734.       }
  1735.     } catch (ex) {
  1736.       // The conversion using the default charset failed. Remove any non-ascii
  1737.       // bytes and try to find a sourceTextEncoding.
  1738.       var asciiBytes = this._data.filter(function (n) {return !(0x80 & n);});
  1739.       var asciiString = String.fromCharCode.apply(null, asciiBytes);
  1740.       sherlockLines = asciiString.split(NEW_LINES).filter(isUsefulLine);
  1741.       searchSection = getSection(sherlockLines, "search");
  1742.       sourceTextEncoding = parseInt(searchSection["sourcetextencoding"]);
  1743.       if (sourceTextEncoding) {
  1744.         sherlockLines = sherlockBytesToLines(this._data, sourceTextEncoding);
  1745.         searchSection = getSection(sherlockLines, "search");
  1746.         browserSection = getSection(sherlockLines, "browser");
  1747.       } else
  1748.         ERROR("Couldn't find a working charset", Cr.NS_ERROR_FAILURE);
  1749.     }
  1750.  
  1751.     LOG("_parseAsSherlock: Search section:\n" + searchSection.toSource());
  1752.  
  1753.     this._name = searchSection["name"] || err("Missing name!");
  1754.     this._description = searchSection["description"] || "";
  1755.     this._queryCharset = searchSection["querycharset"] ||
  1756.                          queryCharsetFromCode(searchSection["queryencoding"]);
  1757.     this._searchForm = searchSection["searchform"];
  1758.  
  1759.     this._updateInterval = parseInt(browserSection["updatecheckdays"]);
  1760.  
  1761.     this._updateURL = browserSection["update"];
  1762.     this._iconUpdateURL = browserSection["updateicon"];
  1763.  
  1764.     var method = (searchSection["method"] || "GET").toUpperCase();
  1765.     var template = searchSection["action"] || err("Missing action!");
  1766.  
  1767.     var inputs = getInputs(sherlockLines);
  1768.     LOG("_parseAsSherlock: Inputs:\n" + inputs.toSource());
  1769.  
  1770.     var url = null;
  1771.  
  1772.     if (method == "GET") {
  1773.       // Here's how we construct the input string:
  1774.       // <input> is first:  Name Attr:  Prefix      Data           Example:
  1775.       // YES                EMPTY       None        <value>        TEMPLATE<value>
  1776.       // YES                NON-EMPTY   ?           <name>=<value> TEMPLATE?<name>=<value>
  1777.       // NO                 EMPTY       ------------- <ignored> --------------
  1778.       // NO                 NON-EMPTY   &           <name>=<value> TEMPLATE?<n1>=<v1>&<n2>=<v2>
  1779.       for (var i = 0; i < inputs.length; i++) {
  1780.         var name  = inputs[i][0];
  1781.         var value = inputs[i][1];
  1782.         if (i==0) {
  1783.           if (name == "")
  1784.             template += USER_DEFINED;
  1785.           else
  1786.             template += "?" + name + "=" + value;
  1787.         } else if (name != "")
  1788.           template += "&" + name + "=" + value;
  1789.       }
  1790.       url = new EngineURL("text/html", method, template);
  1791.  
  1792.     } else if (method == "POST") {
  1793.       // Create the URL object and just add the parameters directly
  1794.       url = new EngineURL("text/html", method, template);
  1795.       for (var i = 0; i < inputs.length; i++) {
  1796.         var name  = inputs[i][0];
  1797.         var value = inputs[i][1];
  1798.         if (name)
  1799.           url.addParam(name, value);
  1800.       }
  1801.     } else
  1802.       err("Invalid method!");
  1803.  
  1804.     this._urls.push(url);
  1805.   },
  1806.  
  1807.   /**
  1808.    * Returns an XML document object containing the search plugin information,
  1809.    * which can later be used to reload the engine.
  1810.    */
  1811.   _serializeToElement: function SRCH_ENG_serializeToEl() {
  1812.     function appendTextNode(aNameSpace, aLocalName, aValue) {
  1813.       if (!aValue)
  1814.         return null;
  1815.       var node = doc.createElementNS(aNameSpace, aLocalName);
  1816.       node.appendChild(doc.createTextNode(aValue));
  1817.       docElem.appendChild(node);
  1818.       docElem.appendChild(doc.createTextNode("\n"));
  1819.       return node;
  1820.     }
  1821.  
  1822.     var parser = Cc["@mozilla.org/xmlextras/domparser;1"].
  1823.                  createInstance(Ci.nsIDOMParser);
  1824.  
  1825.     var doc = parser.parseFromString(EMPTY_DOC, "text/xml");
  1826.     var docElem = doc.documentElement;
  1827.  
  1828.     docElem.appendChild(doc.createTextNode("\n"));
  1829.  
  1830.     appendTextNode(OPENSEARCH_NS_11, "ShortName", this.name);
  1831.     appendTextNode(OPENSEARCH_NS_11, "Description", this._description);
  1832.     appendTextNode(OPENSEARCH_NS_11, "InputEncoding", this._queryCharset);
  1833.  
  1834.     if (this._iconURI) {
  1835.       var imageNode = appendTextNode(OPENSEARCH_NS_11, "Image",
  1836.                                      this._iconURI.spec);
  1837.       if (imageNode) {
  1838.         imageNode.setAttribute("width", "16");
  1839.         imageNode.setAttribute("height", "16");
  1840.       }
  1841.     }
  1842.  
  1843.     appendTextNode(MOZSEARCH_NS_10, "UpdateInterval", this._updateInterval);
  1844.     appendTextNode(MOZSEARCH_NS_10, "UpdateUrl", this._updateURL);
  1845.     appendTextNode(MOZSEARCH_NS_10, "IconUpdateUrl", this._iconUpdateURL);
  1846.     appendTextNode(MOZSEARCH_NS_10, "SearchForm", this._searchForm);
  1847.  
  1848.     for (var i = 0; i < this._urls.length; ++i)
  1849.       this._urls[i]._serializeToElement(doc, docElem);
  1850.     docElem.appendChild(doc.createTextNode("\n"));
  1851.  
  1852.     return doc;
  1853.   },
  1854.  
  1855.   _lazySerializeToFile: function SRCH_ENG_serializeToFile() {
  1856.     if (this._serializeTimer) {
  1857.       // Reset the timer
  1858.       this._serializeTimer.delay = LAZY_SERIALIZE_DELAY;
  1859.     } else {
  1860.       this._serializeTimer = Cc["@mozilla.org/timer;1"].
  1861.                              createInstance(Ci.nsITimer);
  1862.       var timerCallback = {
  1863.         self: this,
  1864.         notify: function SRCH_ENG_notify(aTimer) {
  1865.           try {
  1866.             this.self._serializeToFile();
  1867.           } catch (ex) {
  1868.             LOG("Serialization from timer callback failed:\n" + ex);
  1869.           }
  1870.           this.self._serializeTimer = null;
  1871.         }
  1872.       };
  1873.       this._serializeTimer.initWithCallback(timerCallback,
  1874.                                             LAZY_SERIALIZE_DELAY,
  1875.                                             Ci.nsITimer.TYPE_ONE_SHOT);
  1876.     }
  1877.   },
  1878.  
  1879.   /**
  1880.    * Serializes the engine object to file.
  1881.    */
  1882.   _serializeToFile: function SRCH_ENG_serializeToFile() {
  1883.     var file = this._file;
  1884.     ENSURE_WARN(!this._readOnly, "Can't serialize a read only engine!",
  1885.                 Cr.NS_ERROR_FAILURE);
  1886.     ENSURE_WARN(file && file.exists(), "Can't serialize: file doesn't exist!",
  1887.                 Cr.NS_ERROR_UNEXPECTED);
  1888.  
  1889.     var fos = Cc["@mozilla.org/network/safe-file-output-stream;1"].
  1890.               createInstance(Ci.nsIFileOutputStream);
  1891.  
  1892.     // Serialize the engine first - we don't want to overwrite a good file
  1893.     // if this somehow fails.
  1894.     var doc = this._serializeToElement();
  1895.  
  1896.     fos.init(file, (MODE_WRONLY | MODE_TRUNCATE), PERMS_FILE, 0);
  1897.  
  1898.     try {
  1899.       var serializer = Cc["@mozilla.org/xmlextras/xmlserializer;1"].
  1900.                        createInstance(Ci.nsIDOMSerializer);
  1901.       serializer.serializeToStream(doc.documentElement, fos, null);
  1902.     } catch (e) {
  1903.       LOG("_serializeToFile: Error serializing engine:\n" + e);
  1904.     }
  1905.  
  1906.     closeSafeOutputStream(fos);
  1907.   },
  1908.  
  1909.   /**
  1910.    * Remove the engine's file from disk. The search service calls this once it
  1911.    * removes the engine from its internal store. This function will throw if
  1912.    * the file cannot be removed.
  1913.    */
  1914.   _remove: function SRCH_ENG_remove() {
  1915.     ENSURE(!this._readOnly, "Can't remove read only engine!",
  1916.            Cr.NS_ERROR_FAILURE);
  1917.     ENSURE(this._file && this._file.exists(),
  1918.            "Can't remove engine: file doesn't exist!",
  1919.            Cr.NS_ERROR_FILE_NOT_FOUND);
  1920.  
  1921.     this._file.remove(false);
  1922.   },
  1923.  
  1924.   // nsISearchEngine
  1925.   get alias() {
  1926.     if (this._alias === null)
  1927.       this._alias = engineMetadataService.getAttr(this, "alias");
  1928.  
  1929.     return this._alias;
  1930.   },
  1931.   set alias(val) {
  1932.     this._alias = val;
  1933.     engineMetadataService.setAttr(this, "alias", val);
  1934.     notifyAction(this, SEARCH_ENGINE_CHANGED);
  1935.   },
  1936.  
  1937.   get description() {
  1938.     return this._description;
  1939.   },
  1940.  
  1941.   get hidden() {
  1942.     if (this._hidden === null)
  1943.       this._hidden = engineMetadataService.getAttr(this, "hidden");
  1944.     return this._hidden;
  1945.   },
  1946.   set hidden(val) {
  1947.     var value = !!val;
  1948.     if (value != this._hidden) {
  1949.       this._hidden = value;
  1950.       engineMetadataService.setAttr(this, "hidden", value);
  1951.       notifyAction(this, SEARCH_ENGINE_CHANGED);
  1952.     }
  1953.   },
  1954.  
  1955.   get iconURI() {
  1956.     return this._iconURI;
  1957.   },
  1958.  
  1959.   get _iconURL() {
  1960.     if (!this._iconURI)
  1961.       return "";
  1962.     return this._iconURI.spec;
  1963.   },
  1964.  
  1965.   // Where the engine is being loaded from: will return the URI's spec if the
  1966.   // engine is being downloaded and does not yet have a file. This is only used
  1967.   // for logging.
  1968.   get _location() {
  1969.     if (this._file)
  1970.       return this._file.path;
  1971.  
  1972.     if (this._uri)
  1973.       return this._uri.spec;
  1974.  
  1975.     return "";
  1976.   },
  1977.  
  1978.   // The file that the plugin is loaded from is a unique identifier for it.  We
  1979.   // use this as the identifier to store data in the sqlite database
  1980.   get _id() {
  1981.     ENSURE_WARN(this._file, "No _file for id!", Cr.NS_ERROR_FAILURE);
  1982.  
  1983.     if (this._isInProfile)
  1984.       return "[profile]/" + this._file.leafName;
  1985.  
  1986.     if (this._isInAppDir)
  1987.       return "[app]/" + this._file.leafName;
  1988.  
  1989.     // We're not in the profile or appdir, so this must be an extension-shipped
  1990.     // plugin. Use the full path.
  1991.     return this._file.path;
  1992.   },
  1993.  
  1994.   get _installLocation() {
  1995.     ENSURE_WARN(this._file && this._file.exists(),
  1996.                 "_installLocation: engine has no file!",
  1997.                 Cr.NS_ERROR_FAILURE);
  1998.  
  1999.     if (this.__installLocation === null) {
  2000.       if (this._file.parent.equals(getDir(NS_APP_SEARCH_DIR)))
  2001.         this.__installLocation = SEARCH_APP_DIR;
  2002.       else if (this._file.parent.equals(getDir(NS_APP_USER_SEARCH_DIR)))
  2003.         this.__installLocation = SEARCH_PROFILE_DIR;
  2004.       else
  2005.         this.__installLocation = SEARCH_IN_EXTENSION;
  2006.     }
  2007.  
  2008.     return this.__installLocation;
  2009.   },
  2010.  
  2011.   get _isInAppDir() {
  2012.     return this._installLocation == SEARCH_APP_DIR;
  2013.   },
  2014.   get _isInProfile() {
  2015.     return this._installLocation == SEARCH_PROFILE_DIR;
  2016.   },
  2017.  
  2018.   get _isDefault() {
  2019.     // For now, our concept of a "default engine" is "one that is not in the
  2020.     // user's profile directory", which is currently equivalent to "is app- or
  2021.     // extension-shipped".
  2022.     return !this._isInProfile;
  2023.   },
  2024.  
  2025.   get _hasUpdates() {
  2026.     // Whether or not the engine has an update URL
  2027.     return !!(this._updateURL || this._iconUpdateURL);
  2028.   },
  2029.  
  2030.   get name() {
  2031.     return this._name;
  2032.   },
  2033.  
  2034.   get type() {
  2035.     return this._type;
  2036.   },
  2037.  
  2038.   get searchForm() {
  2039.     if (!this._searchForm) {
  2040.       // No searchForm specified in the engine definition file, use the prePath
  2041.       // (e.g. https://foo.com for https://foo.com/search.php?q=bar).
  2042.       var htmlUrl = this._getURLOfType(URLTYPE_SEARCH_HTML);
  2043.       ENSURE_WARN(htmlUrl, "Engine has no HTML URL!", Cr.NS_ERROR_UNEXPECTED);
  2044.       this._searchForm = makeURI(htmlUrl.template).prePath;
  2045.     }
  2046.  
  2047.     return this._searchForm;
  2048.   },
  2049.  
  2050.   get queryCharset() {
  2051.     if (this._queryCharset)
  2052.       return this._queryCharset;
  2053.     return this._queryCharset = queryCharsetFromCode(/* get the default */);
  2054.   },
  2055.  
  2056.   // from nsISearchEngine
  2057.   addParam: function SRCH_ENG_addParam(aName, aValue, aResponseType) {
  2058.     ENSURE_ARG(aName && (aValue != null),
  2059.                "missing name or value for nsISearchEngine::addParam!");
  2060.     ENSURE_WARN(!this._readOnly,
  2061.                 "called nsISearchEngine::addParam on a read-only engine!",
  2062.                 Cr.NS_ERROR_FAILURE);
  2063.     if (!aResponseType)
  2064.       aResponseType = URLTYPE_SEARCH_HTML;
  2065.  
  2066.     var url = this._getURLOfType(aResponseType);
  2067.  
  2068.     ENSURE(url, "Engine object has no URL for response type " + aResponseType,
  2069.            Cr.NS_ERROR_FAILURE);
  2070.  
  2071.     url.addParam(aName, aValue);
  2072.  
  2073.     // Serialize the changes to file lazily
  2074.     this._lazySerializeToFile();
  2075.   },
  2076.  
  2077.   // from nsISearchEngine
  2078.   getSubmission: function SRCH_ENG_getSubmission(aData, aResponseType) {
  2079.     if (!aResponseType)
  2080.       aResponseType = URLTYPE_SEARCH_HTML;
  2081.  
  2082.     var url = this._getURLOfType(aResponseType);
  2083.  
  2084.     if (!url)
  2085.       return null;
  2086.  
  2087.     if (!aData) {
  2088.       // Return a dummy submission object with our searchForm attribute
  2089.       return new Submission(makeURI(this.searchForm), null);
  2090.     }
  2091.  
  2092.     LOG("getSubmission: In data: \"" + aData + "\"");
  2093.     var textToSubURI = Cc["@mozilla.org/intl/texttosuburi;1"].
  2094.                        getService(Ci.nsITextToSubURI);
  2095.     var data = "";
  2096.     try {
  2097.       data = textToSubURI.ConvertAndEscape(this.queryCharset, aData);
  2098.     } catch (ex) {
  2099.       LOG("getSubmission: Falling back to default queryCharset!");
  2100.       data = textToSubURI.ConvertAndEscape(DEFAULT_QUERY_CHARSET, aData);
  2101.     }
  2102.     LOG("getSubmission: Out data: \"" + data + "\"");
  2103.     return url.getSubmission(data, this);
  2104.   },
  2105.  
  2106.   // from nsISearchEngine
  2107.   supportsResponseType: function SRCH_ENG_supportsResponseType(type) {
  2108.     return (this._getURLOfType(type) != null);
  2109.   },
  2110.  
  2111.   // nsISupports
  2112.   QueryInterface: function SRCH_ENG_QI(aIID) {
  2113.     if (aIID.equals(Ci.nsISearchEngine) ||
  2114.         aIID.equals(Ci.nsISupports))
  2115.       return this;
  2116.     throw Cr.NS_ERROR_NO_INTERFACE;
  2117.   },
  2118.  
  2119.   get wrappedJSObject() {
  2120.     return this;
  2121.   }
  2122.  
  2123. };
  2124.  
  2125. // nsISearchSubmission
  2126. function Submission(aURI, aPostData) {
  2127.   this._uri = aURI;
  2128.   this._postData = aPostData;
  2129. }
  2130. Submission.prototype = {
  2131.   get uri() {
  2132.     return this._uri;
  2133.   },
  2134.   get postData() {
  2135.     return this._postData;
  2136.   },
  2137.   QueryInterface: function SRCH_SUBM_QI(aIID) {
  2138.     if (aIID.equals(Ci.nsISearchSubmission) ||
  2139.         aIID.equals(Ci.nsISupports))
  2140.       return this;
  2141.     throw Cr.NS_ERROR_NO_INTERFACE;
  2142.   }
  2143. }
  2144.  
  2145. // nsIBrowserSearchService
  2146. function SearchService() {
  2147.   this._init();
  2148. }
  2149. SearchService.prototype = {
  2150.   _engines: { },
  2151.   _sortedEngines: null,
  2152.   // Whether or not we need to write the order of engines on shutdown. This
  2153.   // needs to happen anytime _sortedEngines is modified after initial startup. 
  2154.   _needToSetOrderPrefs: false,
  2155.  
  2156.   _init: function() {
  2157.     var prefB = Cc["@mozilla.org/preferences-service;1"].
  2158.                 getService(Ci.nsIPrefBranch);
  2159.     var shouldLog = false;
  2160.     try {
  2161.       shouldLog = prefB.getBoolPref(BROWSER_SEARCH_PREF + "log");
  2162.     } catch (ex) {}
  2163.  
  2164.     if (shouldLog) {
  2165.       // Replace the empty LOG function with the useful one
  2166.       LOG = DO_LOG;
  2167.     }
  2168.  
  2169.     engineMetadataService.init();
  2170.     engineUpdateService.init();
  2171.  
  2172.     this._addObservers();
  2173.  
  2174.     var fileLocator = Cc["@mozilla.org/file/directory_service;1"].
  2175.                       getService(Ci.nsIProperties);
  2176.     var locations = fileLocator.get(NS_APP_SEARCH_DIR_LIST,
  2177.                                     Ci.nsISimpleEnumerator);
  2178.  
  2179.     while (locations.hasMoreElements()) {
  2180.       var location = locations.getNext().QueryInterface(Ci.nsIFile);
  2181.       this._loadEngines(location);
  2182.     }
  2183.  
  2184.     // Now that all engines are loaded, build the sorted engine list
  2185.     this._buildSortedEngineList();
  2186.  
  2187.     selectedEngineName = getLocalizedPref(BROWSER_SEARCH_PREF +
  2188.                                           "selectedEngine");
  2189.     this._currentEngine = this.getEngineByName(selectedEngineName) ||
  2190.                           this.defaultEngine;
  2191.   },
  2192.  
  2193.   _addEngineToStore: function SRCH_SVC_addEngineToStore(aEngine) {
  2194.     LOG("_addEngineToStore: Adding engine: \"" + aEngine.name + "\"");
  2195.  
  2196.     // See if there is an existing engine with the same name. However, if this
  2197.     // engine is updating another engine, it's allowed to have the same name.
  2198.     var hasSameNameAsUpdate = (aEngine._engineToUpdate &&
  2199.                                aEngine.name == aEngine._engineToUpdate.name);
  2200.     if (aEngine.name in this._engines && !hasSameNameAsUpdate) {
  2201.       LOG("_addEngineToStore: Duplicate engine found, aborting!");
  2202.       return;
  2203.     }
  2204.  
  2205.     if (aEngine._engineToUpdate) {
  2206.       // We need to replace engineToUpdate with the engine that just loaded.
  2207.       var oldEngine = aEngine._engineToUpdate;
  2208.  
  2209.       // Remove the old engine from the hash, since it's keyed by name, and our
  2210.       // name might change (the update might have a new name).
  2211.       delete this._engines[oldEngine.name];
  2212.  
  2213.       // Hack: we want to replace the old engine with the new one, but since
  2214.       // people may be holding refs to the nsISearchEngine objects themselves,
  2215.       // we'll just copy over all "private" properties (those without a getter
  2216.       // or setter) from one object to the other.
  2217.       for (var p in aEngine) {
  2218.         if (!(aEngine.__lookupGetter__(p) || aEngine.__lookupSetter__(p)))
  2219.           oldEngine[p] = aEngine[p];
  2220.       }
  2221.       aEngine = oldEngine;
  2222.       aEngine._engineToUpdate = null;
  2223.  
  2224.       // Add the engine back
  2225.       this._engines[aEngine.name] = aEngine;
  2226.       notifyAction(aEngine, SEARCH_ENGINE_CHANGED);
  2227.     } else {
  2228.       // Not an update, just add the new engine.
  2229.       this._engines[aEngine.name] = aEngine;
  2230.       // Only add the engine to the list of sorted engines if the initial list
  2231.       // has already been built (i.e. if this._sortedEngines is non-null). If
  2232.       // it hasn't, we're still loading engines from disk, and will build the
  2233.       // sorted engine list when that initial loading is done.
  2234.       if (this._sortedEngines) {
  2235.         this._sortedEngines.push(aEngine);
  2236.         this._needToSetOrderPrefs = true;
  2237.       }
  2238.       notifyAction(aEngine, SEARCH_ENGINE_ADDED);
  2239.     }
  2240.  
  2241.     if (aEngine._hasUpdates) {
  2242.       // Schedule the engine's next update, if it isn't already.
  2243.       if (!engineMetadataService.getAttr(aEngine, "updateexpir"))
  2244.         engineUpdateService.scheduleNextUpdate(aEngine);
  2245.   
  2246.       // We need to save the engine's _dataType, if this is the first time the
  2247.       // engine is added to the dataStore, since ._dataType isn't persisted
  2248.       // and will change on the next startup (since the engine will then be
  2249.       // XML). We need this so that we know how to load any future updates from
  2250.       // this engine.
  2251.       if (!engineMetadataService.getAttr(aEngine, "updatedatatype"))
  2252.         engineMetadataService.setAttr(aEngine, "updatedatatype",
  2253.                                       aEngine._dataType);
  2254.     }
  2255.   },
  2256.  
  2257.   _loadEngines: function SRCH_SVC_loadEngines(aDir) {
  2258.     LOG("_loadEngines: Searching in " + aDir.path + " for search engines.");
  2259.  
  2260.     // Check whether aDir is the user profile dir
  2261.     var isInProfile = aDir.equals(getDir(NS_APP_USER_SEARCH_DIR));
  2262.  
  2263.     var files = aDir.directoryEntries
  2264.                     .QueryInterface(Ci.nsIDirectoryEnumerator);
  2265.     var ios = Cc["@mozilla.org/network/io-service;1"].
  2266.               getService(Ci.nsIIOService);
  2267.  
  2268.     while (files.hasMoreElements()) {
  2269.       var file = files.nextFile;
  2270.  
  2271.       // Ignore hidden and empty files, and directories
  2272.       if (!file.isFile() || file.fileSize == 0 || file.isHidden())
  2273.         continue;
  2274.  
  2275.       var fileURL = ios.newFileURI(file).QueryInterface(Ci.nsIURL);
  2276.       var fileExtension = fileURL.fileExtension.toLowerCase();
  2277.       var isWritable = isInProfile && file.isWritable();
  2278.  
  2279.       var dataType;
  2280.       switch (fileExtension) {
  2281.         case XML_FILE_EXT:
  2282.           dataType = SEARCH_DATA_XML;
  2283.           break;
  2284.         case SHERLOCK_FILE_EXT:
  2285.           dataType = SEARCH_DATA_TEXT;
  2286.           break;
  2287.         default:
  2288.           // Not an engine
  2289.           continue;
  2290.       }
  2291.  
  2292.       var addedEngine = null;
  2293.       try {
  2294.         addedEngine = new Engine(file, dataType, !isWritable);
  2295.         addedEngine._initFromFile();
  2296.       } catch (ex) {
  2297.         LOG("_loadEngines: Failed to load " + file.path + "!\n" + ex);
  2298.         continue;
  2299.       }
  2300.  
  2301.       if (fileExtension == SHERLOCK_FILE_EXT) {
  2302.         if (isWritable) {
  2303.           try {
  2304.             this._convertSherlockFile(addedEngine, fileURL.fileBaseName);
  2305.           } catch (ex) {
  2306.             LOG("_loadEngines: Failed to convert: " + fileURL.path + "\n" + ex);
  2307.             // The engine couldn't be converted, mark it as read-only
  2308.             addedEngine._readOnly = true;
  2309.           }
  2310.         }
  2311.  
  2312.         // If the engine still doesn't have an icon, see if we can find one
  2313.         if (!addedEngine._iconURI) {
  2314.           var icon = this._findSherlockIcon(file, fileURL.fileBaseName);
  2315.           if (icon)
  2316.             addedEngine._iconURI = ios.newFileURI(icon);
  2317.         }
  2318.       }
  2319.  
  2320.       this._addEngineToStore(addedEngine);
  2321.     }
  2322.   },
  2323.  
  2324.   _saveSortedEngineList: function SRCH_SVC_saveSortedEngineList() {
  2325.     // We only need to write the prefs. if something has changed.
  2326.     if (!this._needToSetOrderPrefs)
  2327.       return;
  2328.  
  2329.     // Set the useDB pref to indicate that from now on we should use the order
  2330.     // information stored in the database.
  2331.     var prefB = Cc["@mozilla.org/preferences-service;1"].
  2332.                 getService(Ci.nsIPrefBranch);
  2333.     prefB.setBoolPref(BROWSER_SEARCH_PREF + "useDBForOrder", true);
  2334.  
  2335.     var engines = this._getSortedEngines(true);
  2336.     var values = [];
  2337.     var names = [];
  2338.  
  2339.     for (var i = 0; i < engines.length; ++i) {
  2340.       names[i] = "order";
  2341.       values[i] = i + 1;
  2342.     }
  2343.  
  2344.     engineMetadataService.setAttrs(engines, names, values);
  2345.   },
  2346.  
  2347.   _buildSortedEngineList: function SRCH_SVC_buildSortedEngineList() {
  2348.     var addedEngines = { };
  2349.     this._sortedEngines = [];
  2350.     var engine;
  2351.  
  2352.     // If the user has specified a custom engine order, read the order
  2353.     // information from the engineMetadataService instead of the default
  2354.     // prefs.
  2355.     if (getBoolPref(BROWSER_SEARCH_PREF + "useDBForOrder", false)) {
  2356.       for each (engine in this._engines) {
  2357.         var orderNumber = engineMetadataService.getAttr(engine, "order");
  2358.  
  2359.         // Since the DB isn't regularly cleared, and engine files may disappear
  2360.         // without us knowing, we may already have an engine in this slot. If
  2361.         // that happens, we just skip it - it will be added later on as an
  2362.         // unsorted engine. This problem will sort itself out when we call
  2363.         // _saveSortedEngineList at shutdown.
  2364.         if (orderNumber && !this._sortedEngines[orderNumber-1]) {
  2365.           this._sortedEngines[orderNumber-1] = engine;
  2366.           addedEngines[engine.name] = engine;
  2367.         } else {
  2368.           // We need to call _saveSortedEngines so this gets sorted out.
  2369.           this._needToSetOrderPrefs = true;
  2370.         }
  2371.       }
  2372.  
  2373.       // Filter out any nulls for engines that may have been removed
  2374.       var filteredEngines = this._sortedEngines.filter(function(a) { return !!a; });
  2375.       if (this._sortedEngines.length != filteredEngines.length)
  2376.         this._needToSetOrderPrefs = true;
  2377.       this._sortedEngines = filteredEngines;
  2378.  
  2379.     } else {
  2380.       // The DB isn't being used, so just read the engine order from the prefs
  2381.       var i = 0;
  2382.       var engineName;
  2383.       var prefName;
  2384.  
  2385.       try {
  2386.         var prefB = Cc["@mozilla.org/preferences-service;1"].
  2387.                     getService(Ci.nsIPrefBranch);
  2388.         var extras =
  2389.           prefB.getChildList(BROWSER_SEARCH_PREF + "order.extra.", { });
  2390.  
  2391.         for each (prefName in extras) {
  2392.           engineName = prefB.getCharPref(prefName);
  2393.  
  2394.           engine = this._engines[engineName];
  2395.           if (!engine || engine.name in addedEngines)
  2396.             continue;
  2397.  
  2398.           this._sortedEngines.push(engine);
  2399.           addedEngines[engine.name] = engine;
  2400.         }
  2401.       }
  2402.       catch (e) { }
  2403.  
  2404.       while (true) {
  2405.         engineName = getLocalizedPref(BROWSER_SEARCH_PREF + "order." + (++i));
  2406.         if (!engineName)
  2407.           break;
  2408.  
  2409.         engine = this._engines[engineName];
  2410.         if (!engine || engine.name in addedEngines)
  2411.           continue;
  2412.         
  2413.         this._sortedEngines.push(engine);
  2414.         addedEngines[engine.name] = engine;
  2415.       }
  2416.     }
  2417.  
  2418.     // Array for the remaining engines, alphabetically sorted
  2419.     var alphaEngines = [];
  2420.  
  2421.     for each (engine in this._engines) {
  2422.       if (!(engine.name in addedEngines))
  2423.         alphaEngines.push(this._engines[engine.name]);
  2424.     }
  2425.     alphaEngines = alphaEngines.sort(function (a, b) {
  2426.                                        return a.name.localeCompare(b.name);
  2427.                                      });
  2428.     this._sortedEngines = this._sortedEngines.concat(alphaEngines);
  2429.   },
  2430.  
  2431.   /**
  2432.    * Converts a Sherlock file and its icon into the custom XML format used by
  2433.    * the Search Service. Saves the engine's icon (if present) into the XML as a
  2434.    * data: URI and changes the extension of the source file from ".src" to
  2435.    * ".xml". The engine data is then written to the file as XML.
  2436.    * @param aEngine
  2437.    *        The Engine object that needs to be converted.
  2438.    * @param aBaseName
  2439.    *        The basename of the Sherlock file.
  2440.    *          Example: "foo" for file "foo.src".
  2441.    *
  2442.    * @throws NS_ERROR_FAILURE if the file could not be converted.
  2443.    *
  2444.    * @see nsIURL::fileBaseName
  2445.    */
  2446.   _convertSherlockFile: function SRCH_SVC_convertSherlock(aEngine, aBaseName) {
  2447.     var oldSherlockFile = aEngine._file;
  2448.  
  2449.     // Back up the old file
  2450.     try {
  2451.       var backupDir = oldSherlockFile.parent;
  2452.       backupDir.append("searchplugins-backup");
  2453.  
  2454.       if (!backupDir.exists())
  2455.         backupDir.create(Ci.nsIFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  2456.  
  2457.       oldSherlockFile.copyTo(backupDir, null);
  2458.     } catch (ex) {
  2459.       // Just bail. Engines that can't be backed up won't be converted, but
  2460.       // engines that aren't converted are loaded as readonly.
  2461.       LOG("_convertSherlockFile: Couldn't back up " + oldSherlockFile.path +
  2462.           ":\n" + ex);
  2463.       throw Cr.NS_ERROR_FAILURE;
  2464.     }
  2465.  
  2466.     // Rename the file, but don't clobber existing files
  2467.     var newXMLFile = oldSherlockFile.parent.clone();
  2468.     newXMLFile.append(aBaseName + "." + XML_FILE_EXT);
  2469.  
  2470.     if (newXMLFile.exists()) {
  2471.       // There is an existing file with this name, create a unique file
  2472.       newXMLFile.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, PERMS_FILE);
  2473.     }
  2474.  
  2475.     // Rename the .src file to .xml
  2476.     oldSherlockFile.moveTo(null, newXMLFile.leafName);
  2477.  
  2478.     aEngine._file = newXMLFile;
  2479.  
  2480.     // Write the converted engine to disk
  2481.     aEngine._serializeToFile();
  2482.  
  2483.     // Update the engine's _type.
  2484.     aEngine._type = SEARCH_TYPE_MOZSEARCH;
  2485.  
  2486.     // See if it has a corresponding icon
  2487.     try {
  2488.       var icon = this._findSherlockIcon(aEngine._file, aBaseName);
  2489.       if (icon && icon.fileSize < MAX_ICON_SIZE) {
  2490.         // Use this as the engine's icon
  2491.         var bStream = Cc["@mozilla.org/binaryinputstream;1"].
  2492.                         createInstance(Ci.nsIBinaryInputStream);
  2493.         var fileInStream = Cc["@mozilla.org/network/file-input-stream;1"].
  2494.                            createInstance(Ci.nsIFileInputStream);
  2495.  
  2496.         fileInStream.init(icon, MODE_RDONLY, PERMS_FILE, 0);
  2497.         bStream.setInputStream(fileInStream);
  2498.  
  2499.         var bytes = [];
  2500.         while (bStream.available() != 0)
  2501.           bytes = bytes.concat(bStream.readByteArray(bStream.available()));
  2502.         bStream.close();
  2503.  
  2504.         // Convert the byte array to a base64-encoded string
  2505.         var str = btoa(String.fromCharCode.apply(null, bytes));
  2506.  
  2507.         aEngine._iconURI = makeURI(ICON_DATAURL_PREFIX + str);
  2508.         LOG("_importSherlockEngine: Set sherlock iconURI to: \"" +
  2509.             aEngine._iconURL + "\"");
  2510.  
  2511.         // Write the engine to disk to save changes
  2512.         aEngine._serializeToFile();
  2513.  
  2514.         // Delete the icon now that we're sure everything's been saved
  2515.         icon.remove(false);
  2516.       }
  2517.     } catch (ex) { LOG("_convertSherlockFile: Error setting icon:\n" + ex); }
  2518.   },
  2519.  
  2520.   /**
  2521.    * Finds an icon associated to a given Sherlock file. Searches the provided
  2522.    * file's parent directory looking for files with the same base name and one
  2523.    * of the file extensions in SHERLOCK_ICON_EXTENSIONS.
  2524.    * @param aEngineFile
  2525.    *        The Sherlock plugin file.
  2526.    * @param aBaseName
  2527.    *        The basename of the Sherlock file.
  2528.    *          Example: "foo" for file "foo.src".
  2529.    * @see nsIURL::fileBaseName
  2530.    */
  2531.   _findSherlockIcon: function SRCH_SVC_findSherlock(aEngineFile, aBaseName) {
  2532.     for (var i = 0; i < SHERLOCK_ICON_EXTENSIONS.length; i++) {
  2533.       var icon = aEngineFile.parent.clone();
  2534.       icon.append(aBaseName + SHERLOCK_ICON_EXTENSIONS[i]);
  2535.       if (icon.exists() && icon.isFile())
  2536.         return icon;
  2537.     }
  2538.     return null;
  2539.   },
  2540.  
  2541.   /**
  2542.    * Get a sorted array of engines.
  2543.    * @param aWithHidden
  2544.    *        True if hidden plugins should be included in the result.
  2545.    */
  2546.   _getSortedEngines: function SRCH_SVC_getSorted(aWithHidden) {
  2547.     if (aWithHidden)
  2548.       return this._sortedEngines;
  2549.  
  2550.     return this._sortedEngines.filter(function (engine) {
  2551.                                         return !engine.hidden;
  2552.                                       });
  2553.   },
  2554.  
  2555.   // nsIBrowserSearchService
  2556.   getEngines: function SRCH_SVC_getEngines(aCount) {
  2557.     LOG("getEngines: getting all engines");
  2558.     var engines = this._getSortedEngines(true);
  2559.     aCount.value = engines.length;
  2560.     return engines;
  2561.   },
  2562.  
  2563.   getVisibleEngines: function SRCH_SVC_getVisible(aCount) {
  2564.     LOG("getVisibleEngines: getting all visible engines");
  2565.     var engines = this._getSortedEngines(false);
  2566.     aCount.value = engines.length;
  2567.     return engines;
  2568.   },
  2569.  
  2570.   getDefaultEngines: function SRCH_SVC_getDefault(aCount) {
  2571.     function isDefault(engine) {
  2572.       return engine._isDefault;
  2573.     };
  2574.     var engines = this._sortedEngines.filter(isDefault);
  2575.     var engineOrder = {};
  2576.     var engineName;
  2577.     var i = 1;
  2578.  
  2579.     // Build a list of engines which we have ordering information for.
  2580.     // We're rebuilding the list here because _sortedEngines contain the
  2581.     // current order, but we want the original order.
  2582.  
  2583.     // First, look at the "browser.search.order.extra" branch.
  2584.     try {
  2585.       var prefB = Cc["@mozilla.org/preferences-service;1"].
  2586.                   getService(Ci.nsIPrefBranch);
  2587.       var extras = prefB.getChildList(BROWSER_SEARCH_PREF + "order.extra.",
  2588.                                       {});
  2589.  
  2590.       for each (var prefName in extras) {
  2591.         engineName = prefB.getCharPref(prefName);
  2592.  
  2593.         if (!(engineName in engineOrder))
  2594.           engineOrder[engineName] = i++;
  2595.       }
  2596.     } catch (e) {
  2597.       LOG("Getting extra order prefs failed: " + e);
  2598.     }
  2599.  
  2600.     // Now look through the "browser.search.order" branch.
  2601.     for (var j = 1; ; j++) {
  2602.       engineName = getLocalizedPref(BROWSER_SEARCH_PREF + "order." + j);
  2603.       if (!engineName)
  2604.         break;
  2605.  
  2606.       if (!(engineName in engineOrder))
  2607.         engineOrder[engineName] = i++;
  2608.     }
  2609.  
  2610.     LOG("getDefaultEngines: engineOrder: " + engineOrder.toSource());
  2611.  
  2612.     function compareEngines (a, b) {
  2613.       var aIdx = engineOrder[a.name];
  2614.       var bIdx = engineOrder[b.name];
  2615.  
  2616.       if (aIdx && bIdx)
  2617.         return aIdx - bIdx;
  2618.       if (aIdx)
  2619.         return -1;
  2620.       if (bIdx)
  2621.         return 1;
  2622.  
  2623.       return a.name.localeCompare(b.name);
  2624.     }
  2625.     engines.sort(compareEngines);
  2626.  
  2627.     aCount.value = engines.length;
  2628.     return engines;
  2629.   },
  2630.  
  2631.   getEngineByName: function SRCH_SVC_getEngineByName(aEngineName) {
  2632.     return this._engines[aEngineName] || null;
  2633.   },
  2634.  
  2635.   getEngineByAlias: function SRCH_SVC_getEngineByAlias(aAlias) {
  2636.     for (var engineName in this._engines) {
  2637.       var engine = this._engines[engineName];
  2638.       if (engine && engine.alias == aAlias)
  2639.         return engine;
  2640.     }
  2641.     return null;
  2642.   },
  2643.  
  2644.   addEngineWithDetails: function SRCH_SVC_addEWD(aName, aIconURL, aAlias,
  2645.                                                  aDescription, aMethod,
  2646.                                                  aTemplate) {
  2647.     ENSURE_ARG(aName, "Invalid name passed to addEngineWithDetails!");
  2648.     ENSURE_ARG(aMethod, "Invalid method passed to addEngineWithDetails!");
  2649.     ENSURE_ARG(aTemplate, "Invalid template passed to addEngineWithDetails!");
  2650.  
  2651.     ENSURE(!this._engines[aName], "An engine with that name already exists!",
  2652.            Cr.NS_ERROR_FILE_ALREADY_EXISTS);
  2653.  
  2654.     var engine = new Engine(getSanitizedFile(aName), SEARCH_DATA_XML, false);
  2655.     engine._initFromMetadata(aName, aIconURL, aAlias, aDescription,
  2656.                              aMethod, aTemplate);
  2657.     this._addEngineToStore(engine);
  2658.   },
  2659.  
  2660.   addEngine: function SRCH_SVC_addEngine(aEngineURL, aDataType, aIconURL,
  2661.                                          aConfirm) {
  2662.     LOG("addEngine: Adding \"" + aEngineURL + "\".");
  2663.     try {
  2664.       var uri = makeURI(aEngineURL);
  2665.       var engine = new Engine(uri, aDataType, false);
  2666.       engine._initFromURI();
  2667.     } catch (ex) {
  2668.       LOG("addEngine: Error adding engine:\n" + ex);
  2669.       throw Cr.NS_ERROR_FAILURE;
  2670.     }
  2671.     engine._setIcon(aIconURL, false);
  2672.     engine._confirm = aConfirm;
  2673.   },
  2674.  
  2675.   removeEngine: function SRCH_SVC_removeEngine(aEngine) {
  2676.     ENSURE_ARG(aEngine, "no engine passed to removeEngine!");
  2677.  
  2678.     var engineToRemove = null;
  2679.     for (var e in this._engines)
  2680.       if (aEngine.wrappedJSObject == this._engines[e])
  2681.         engineToRemove = this._engines[e];
  2682.  
  2683.     ENSURE(engineToRemove, "removeEngine: Can't find engine to remove!",
  2684.            Cr.NS_ERROR_FILE_NOT_FOUND);
  2685.  
  2686.     if (engineToRemove == this.currentEngine)
  2687.       this._currentEngine = null;
  2688.  
  2689.     if (engineToRemove._readOnly) {
  2690.       // Just hide it (the "hidden" setter will notify) and remove its alias to
  2691.       // avoid future conflicts with other engines.
  2692.       engineToRemove.hidden = true;
  2693.       engineToRemove.alias = null;
  2694.     } else {
  2695.       // Cancel the lazy serialization timer if it's running
  2696.       if (engineToRemove._serializeTimer) {
  2697.         engineToRemove._serializeTimer.cancel();
  2698.         engineToRemove._serializeTimer = null;
  2699.       }
  2700.  
  2701.       // Remove the engine file from disk (this might throw)
  2702.       engineToRemove._remove();
  2703.       engineToRemove._file = null;
  2704.  
  2705.       // Remove the engine from _sortedEngines
  2706.       var index = this._sortedEngines.indexOf(engineToRemove);
  2707.       ENSURE(index != -1, "Can't find engine to remove in _sortedEngines!",
  2708.              Cr.NS_ERROR_FAILURE);
  2709.       this._sortedEngines.splice(index, 1);
  2710.  
  2711.       // Remove the engine from the internal store
  2712.       delete this._engines[engineToRemove.name];
  2713.  
  2714.       notifyAction(engineToRemove, SEARCH_ENGINE_REMOVED);
  2715.  
  2716.       // Since we removed an engine, we need to update the preferences.
  2717.       this._needToSetOrderPrefs = true;
  2718.     }
  2719.   },
  2720.  
  2721.   moveEngine: function SRCH_SVC_moveEngine(aEngine, aNewIndex) {
  2722.     ENSURE_ARG((aNewIndex < this._sortedEngines.length) && (aNewIndex >= 0),
  2723.                "SRCH_SVC_moveEngine: Index out of bounds!");
  2724.     ENSURE_ARG(aEngine instanceof Ci.nsISearchEngine,
  2725.                "SRCH_SVC_moveEngine: Invalid engine passed to moveEngine!");
  2726.     ENSURE(!aEngine.hidden, "moveEngine: Can't move a hidden engine!",
  2727.            Cr.NS_ERROR_FAILURE);
  2728.  
  2729.     var engine = aEngine.wrappedJSObject;
  2730.  
  2731.     var currentIndex = this._sortedEngines.indexOf(engine);
  2732.     ENSURE(currentIndex != -1, "moveEngine: Can't find engine to move!",
  2733.            Cr.NS_ERROR_UNEXPECTED);
  2734.  
  2735.     // Our callers only take into account non-hidden engines when calculating
  2736.     // aNewIndex, but we need to move it in the array of all engines, so we
  2737.     // need to adjust aNewIndex accordingly. To do this, we count the number
  2738.     // of hidden engines in the list before the engine that we're taking the
  2739.     // place of. We do this by first finding newIndexEngine (the engine that
  2740.     // we were supposed to replace) and then iterating through the complete 
  2741.     // engine list until we reach it, increasing aNewIndex for each hidden
  2742.     // engine we find on our way there.
  2743.     //
  2744.     // This could be further simplified by having our caller pass in
  2745.     // newIndexEngine directly instead of aNewIndex.
  2746.     var newIndexEngine = this._getSortedEngines(false)[aNewIndex];
  2747.     ENSURE(newIndexEngine, "moveEngine: Can't find engine to replace!",
  2748.            Cr.NS_ERROR_UNEXPECTED);
  2749.  
  2750.     for (var i = 0; i < this._sortedEngines.length; ++i) {
  2751.       if (newIndexEngine == this._sortedEngines[i])
  2752.         break;
  2753.       if (this._sortedEngines[i].hidden)
  2754.         aNewIndex++;
  2755.     }
  2756.  
  2757.     if (currentIndex == aNewIndex)
  2758.       return; // nothing to do!
  2759.  
  2760.     // Move the engine
  2761.     var movedEngine = this._sortedEngines.splice(currentIndex, 1)[0];
  2762.     this._sortedEngines.splice(aNewIndex, 0, movedEngine);
  2763.  
  2764.     notifyAction(engine, SEARCH_ENGINE_CHANGED);
  2765.  
  2766.     // Since we moved an engine, we need to update the preferences.
  2767.     this._needToSetOrderPrefs = true;
  2768.   },
  2769.  
  2770.   restoreDefaultEngines: function SRCH_SVC_resetDefaultEngines() {
  2771.     for each (var e in this._engines) {
  2772.       // Unhide all default engines
  2773.       if (e.hidden && e._isDefault)
  2774.         e.hidden = false;
  2775.     }
  2776.   },
  2777.  
  2778.   get defaultEngine() {
  2779.     const defPref = BROWSER_SEARCH_PREF + "defaultenginename";
  2780.     // Get the default engine - this pref should always exist, but the engine
  2781.     // might be hidden
  2782.     this._defaultEngine = this.getEngineByName(getLocalizedPref(defPref, ""));
  2783.     if (!this._defaultEngine || this._defaultEngine.hidden)
  2784.       this._defaultEngine = this._getSortedEngines(false)[0] || null;
  2785.     return this._defaultEngine;
  2786.   },
  2787.  
  2788.   get currentEngine() {
  2789.     if (!this._currentEngine || this._currentEngine.hidden)
  2790.       this._currentEngine = this.defaultEngine;
  2791.     return this._currentEngine;
  2792.   },
  2793.   set currentEngine(val) {
  2794.     ENSURE_ARG(val instanceof Ci.nsISearchEngine,
  2795.                "Invalid argument passed to currentEngine setter");
  2796.  
  2797.     var newCurrentEngine = this.getEngineByName(val.name);
  2798.     ENSURE(newCurrentEngine, "Can't find engine in store!",
  2799.            Cr.NS_ERROR_UNEXPECTED);
  2800.  
  2801.     this._currentEngine = newCurrentEngine;
  2802.  
  2803.     var currentEnginePref = BROWSER_SEARCH_PREF + "selectedEngine";
  2804.  
  2805.     var prefB = Cc["@mozilla.org/preferences-service;1"].
  2806.       getService(Ci.nsIPrefService).QueryInterface(Ci.nsIPrefBranch);
  2807.  
  2808.     if (this._currentEngine == this.defaultEngine) {
  2809.       if (prefB.prefHasUserValue(currentEnginePref))
  2810.         prefB.clearUserPref(currentEnginePref);
  2811.     }
  2812.     else {
  2813.       setLocalizedPref(currentEnginePref, this._currentEngine.name);
  2814.     }
  2815.  
  2816.     notifyAction(this._currentEngine, SEARCH_ENGINE_CURRENT);
  2817.   },
  2818.  
  2819.   // nsIObserver
  2820.   observe: function SRCH_SVC_observe(aEngine, aTopic, aVerb) {
  2821.     switch (aTopic) {
  2822.       case SEARCH_ENGINE_TOPIC:
  2823.         if (aVerb == SEARCH_ENGINE_LOADED) {
  2824.           var engine = aEngine.QueryInterface(Ci.nsISearchEngine);
  2825.           LOG("nsSearchService::observe: Done installation of " + engine.name
  2826.               + ".");
  2827.           this._addEngineToStore(engine.wrappedJSObject);
  2828.           if (engine.wrappedJSObject._useNow) {
  2829.             LOG("nsSearchService::observe: setting current");
  2830.             this.currentEngine = aEngine;
  2831.           }
  2832.         }
  2833.         break;
  2834.       case QUIT_APPLICATION_TOPIC:
  2835.         this._removeObservers();
  2836.         this._saveSortedEngineList();
  2837.         break;
  2838.     }
  2839.   },
  2840.  
  2841.   _addObservers: function SRCH_SVC_addObservers() {
  2842.     var os = Cc["@mozilla.org/observer-service;1"].
  2843.              getService(Ci.nsIObserverService);
  2844.     os.addObserver(this, SEARCH_ENGINE_TOPIC, false);
  2845.     os.addObserver(this, QUIT_APPLICATION_TOPIC, false);
  2846.   },
  2847.  
  2848.   _removeObservers: function SRCH_SVC_removeObservers() {
  2849.     var os = Cc["@mozilla.org/observer-service;1"].
  2850.              getService(Ci.nsIObserverService);
  2851.     os.removeObserver(this, SEARCH_ENGINE_TOPIC);
  2852.     os.removeObserver(this, QUIT_APPLICATION_TOPIC);
  2853.   },
  2854.  
  2855.   QueryInterface: function SRCH_SVC_QI(aIID) {
  2856.     if (aIID.equals(Ci.nsIBrowserSearchService) ||
  2857.         aIID.equals(Ci.nsIObserver)             ||
  2858.         aIID.equals(Ci.nsISupports))
  2859.       return this;
  2860.     throw Cr.NS_ERROR_NO_INTERFACE;
  2861.   }
  2862. };
  2863.  
  2864. var engineMetadataService = {
  2865.   init: function epsInit() {
  2866.     var engineDataTable = "id INTEGER PRIMARY KEY, engineid STRING, name STRING, value STRING";
  2867.     var file = getDir(NS_APP_USER_PROFILE_50_DIR);
  2868.     file.append("search.sqlite");
  2869.     var dbService = Cc["@mozilla.org/storage/service;1"].
  2870.                     getService(Ci.mozIStorageService);
  2871.     try {
  2872.         this.mDB = dbService.openDatabase(file);
  2873.     } catch (ex) {
  2874.         if (ex.result == 0x8052000b) { /* NS_ERROR_FILE_CORRUPTED */
  2875.             // delete and try again
  2876.             file.remove(false);
  2877.             this.mDB = dbService.openDatabase(file);
  2878.         } else {
  2879.             throw ex;
  2880.         }
  2881.     }
  2882.  
  2883.     try {
  2884.       this.mDB.createTable("engine_data", engineDataTable);
  2885.     } catch (ex) {
  2886.       // Fails if the table already exists, which is fine
  2887.     }
  2888.  
  2889.     this.mGetData = createStatement (
  2890.       this.mDB,
  2891.       "SELECT value FROM engine_data WHERE engineid = :engineid AND name = :name");
  2892.     this.mDeleteData = createStatement (
  2893.       this.mDB,
  2894.       "DELETE FROM engine_data WHERE engineid = :engineid AND name = :name");
  2895.     this.mInsertData = createStatement (
  2896.       this.mDB,
  2897.       "INSERT INTO engine_data (engineid, name, value) " +
  2898.       "VALUES (:engineid, :name, :value)");
  2899.   },
  2900.   getAttr: function epsGetAttr(engine, name) {
  2901.      // attr names must be lower case
  2902.      name = name.toLowerCase();
  2903.  
  2904.     var stmt = this.mGetData;
  2905.     stmt.reset();
  2906.     var pp = stmt.params;
  2907.     pp.engineid = engine._id;
  2908.     pp.name = name;
  2909.  
  2910.     var value = null;
  2911.     if (stmt.step())
  2912.       value = stmt.row.value;
  2913.     stmt.reset();
  2914.     return value;
  2915.   },
  2916.  
  2917.   setAttr: function epsSetAttr(engine, name, value) {
  2918.     // attr names must be lower case
  2919.     name = name.toLowerCase();
  2920.  
  2921.     this.mDB.beginTransaction();
  2922.  
  2923.     var pp = this.mDeleteData.params;
  2924.     pp.engineid = engine._id;
  2925.     pp.name = name;
  2926.     this.mDeleteData.step();
  2927.     this.mDeleteData.reset();
  2928.  
  2929.     pp = this.mInsertData.params;
  2930.     pp.engineid = engine._id;
  2931.     pp.name = name;
  2932.     pp.value = value;
  2933.     this.mInsertData.step();
  2934.     this.mInsertData.reset();
  2935.  
  2936.     this.mDB.commitTransaction();
  2937.   },
  2938.  
  2939.   setAttrs: function epsSetAttrs(engines, names, values) {
  2940.     this.mDB.beginTransaction();
  2941.  
  2942.     for (var i = 0; i < engines.length; i++) {
  2943.       // attr names must be lower case
  2944.       var name = names[i].toLowerCase();
  2945.  
  2946.       var pp = this.mDeleteData.params;
  2947.       pp.engineid = engines[i]._id;
  2948.       pp.name = names[i];
  2949.       this.mDeleteData.step();
  2950.       this.mDeleteData.reset();
  2951.  
  2952.       pp = this.mInsertData.params;
  2953.       pp.engineid = engines[i]._id;
  2954.       pp.name = names[i];
  2955.       pp.value = values[i];
  2956.       this.mInsertData.step();
  2957.       this.mInsertData.reset();
  2958.     }
  2959.  
  2960.     this.mDB.commitTransaction();
  2961.   },
  2962.  
  2963.   deleteEngineData: function epsDelData(engine, name) {
  2964.     // attr names must be lower case
  2965.     name = name.toLowerCase();
  2966.  
  2967.     var pp = this.mDeleteData.params;
  2968.     pp.engineid = engine._id;
  2969.     pp.name = name;
  2970.     this.mDeleteData.step();
  2971.     this.mDeleteData.reset();
  2972.   }
  2973. }
  2974.  
  2975. const SEARCH_UPDATE_LOG_PREFIX = "*** Search update: ";
  2976.  
  2977. /**
  2978.  * Outputs aText to the JavaScript console as well as to stdout, if the search
  2979.  * logging pref (browser.search.update.log) is set to true.
  2980.  */
  2981. function ULOG(aText) {
  2982.   var prefB = Cc["@mozilla.org/preferences-service;1"].
  2983.               getService(Ci.nsIPrefBranch);
  2984.   var shouldLog = false;
  2985.   try {
  2986.     shouldLog = prefB.getBoolPref(BROWSER_SEARCH_PREF + "update.log");
  2987.   } catch (ex) {}
  2988.  
  2989.   if (shouldLog) {
  2990.     dump(SEARCH_UPDATE_LOG_PREFIX + aText + "\n");
  2991.     var consoleService = Cc["@mozilla.org/consoleservice;1"].
  2992.                          getService(Ci.nsIConsoleService);
  2993.     consoleService.logStringMessage(aText);
  2994.   }
  2995. }
  2996.  
  2997. var engineUpdateService = {
  2998.   init: function eus_init() {
  2999.     var tm = Cc["@mozilla.org/updates/timer-manager;1"].
  3000.              getService(Ci.nsIUpdateTimerManager);
  3001.     // figure out how often to check for any expired engines
  3002.     var prefB = Cc["@mozilla.org/preferences-service;1"].
  3003.                 getService(Ci.nsIPrefBranch);
  3004.     var interval = prefB.getIntPref(BROWSER_SEARCH_PREF + "updateinterval");
  3005.  
  3006.     // Interval is stored in hours
  3007.     var seconds = interval * 3600;
  3008.     tm.registerTimer("search-engine-update-timer", engineUpdateService,
  3009.                      seconds);
  3010.   },
  3011.  
  3012.   scheduleNextUpdate: function eus_scheduleNextUpdate(aEngine) {
  3013.     var interval = aEngine._updateInterval || SEARCH_DEFAULT_UPDATE_INTERVAL;
  3014.     var milliseconds = interval * 86400000; // |interval| is in days
  3015.     engineMetadataService.setAttr(aEngine, "updateexpir",
  3016.                                   Date.now() + milliseconds);
  3017.   },
  3018.  
  3019.   notify: function eus_Notify(aTimer) {
  3020.     ULOG("notify called");
  3021.  
  3022.     if (!getBoolPref(BROWSER_SEARCH_PREF + "update", true))
  3023.       return;
  3024.  
  3025.     // Our timer has expired, but unfortunately, we can't get any data from it.
  3026.     // Therefore, we need to walk our engine-list, looking for expired engines
  3027.     var searchService = Cc["@mozilla.org/browser/search-service;1"].
  3028.                         getService(Ci.nsIBrowserSearchService);
  3029.     var currentTime = Date.now();
  3030.     ULOG("currentTime: " + currentTime);
  3031.     for each (engine in searchService.getEngines({})) {
  3032.       engine = engine.wrappedJSObject;
  3033.       if (!engine._hasUpdates || engine._readOnly)
  3034.         continue;
  3035.  
  3036.       ULOG("checking " + engine.name);
  3037.  
  3038.       var expirTime = engineMetadataService.getAttr(engine, "updateexpir");
  3039.       var updateURL = engine._updateURL;
  3040.       var iconUpdateURL = engine._iconUpdateURL;
  3041.       ULOG("expirTime: " + expirTime + "\nupdateURL: " + updateURL +
  3042.            "\niconUpdateURL: " + iconUpdateURL);
  3043.  
  3044.       var engineExpired = expirTime <= currentTime;
  3045.  
  3046.       if (!expirTime || !engineExpired) {
  3047.         ULOG("skipping engine");
  3048.         continue;
  3049.       }
  3050.  
  3051.       ULOG(engine.name + " has expired");
  3052.  
  3053.       var testEngine = null;
  3054.  
  3055.       var updateURI = makeURI(updateURL);
  3056.       if (updateURI) {
  3057.         var dataType = engineMetadataService.getAttr(engine, "updatedatatype")
  3058.         if (!dataType) {
  3059.           ULOG("No loadtype to update engine!");
  3060.           continue;
  3061.         }
  3062.  
  3063.         testEngine = new Engine(updateURI, dataType, false);
  3064.         testEngine._engineToUpdate = engine;
  3065.         testEngine._initFromURI();
  3066.       } else
  3067.         ULOG("invalid updateURI");
  3068.  
  3069.       if (iconUpdateURL) {
  3070.         // If we're updating the engine too, use the new engine object,
  3071.         // otherwise use the existing engine object.
  3072.         (testEngine || engine)._setIcon(iconUpdateURL, true);
  3073.       }
  3074.  
  3075.       // Schedule the next update
  3076.       this.scheduleNextUpdate(engine);
  3077.  
  3078.     } // end engine iteration
  3079.   }
  3080. };
  3081.  
  3082. const kClassID    = Components.ID("{7319788a-fe93-4db3-9f39-818cf08f4256}");
  3083. const kClassName  = "Browser Search Service";
  3084. const kContractID = "@mozilla.org/browser/search-service;1";
  3085.  
  3086. // nsIFactory
  3087. const kFactory = {
  3088.   createInstance: function (outer, iid) {
  3089.     if (outer != null)
  3090.       throw Cr.NS_ERROR_NO_AGGREGATION;
  3091.     return (new SearchService()).QueryInterface(iid);
  3092.   }
  3093. };
  3094.  
  3095. // nsIModule
  3096. const gModule = {
  3097.   registerSelf: function (componentManager, fileSpec, location, type) {
  3098.     componentManager.QueryInterface(Ci.nsIComponentRegistrar);
  3099.     componentManager.registerFactoryLocation(kClassID,
  3100.                                              kClassName,
  3101.                                              kContractID,
  3102.                                              fileSpec, location, type);
  3103.   },
  3104.  
  3105.   unregisterSelf: function(componentManager, fileSpec, location) {
  3106.     componentManager.QueryInterface(Ci.nsIComponentRegistrar);
  3107.     componentManager.unregisterFactoryLocation(kClassID, fileSpec);
  3108.   },
  3109.  
  3110.   getClassObject: function (componentManager, cid, iid) {
  3111.     if (!cid.equals(kClassID))
  3112.       throw Cr.NS_ERROR_NO_INTERFACE;
  3113.     if (!iid.equals(Ci.nsIFactory))
  3114.       throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  3115.     return kFactory;
  3116.   },
  3117.  
  3118.   canUnload: function (componentManager) {
  3119.     return true;
  3120.   }
  3121. };
  3122.  
  3123. function NSGetModule(componentManager, fileSpec) {
  3124.   return gModule;
  3125. }
  3126.  
  3127. //@line 44 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\content\debug.js"
  3128.  
  3129. var EXPORTED_SYMBOLS = ["NS_ASSERT"];
  3130.  
  3131. var gTraceOnAssert = true;
  3132.  
  3133. /**
  3134.  * This function provides a simple assertion function for JavaScript.
  3135.  * If the condition is true, this function will do nothing.  If the
  3136.  * condition is false, then the message will be printed to the console
  3137.  * and an alert will appear showing a stack trace, so that the (alpha
  3138.  * or nightly) user can file a bug containing it.  For future enhancements, 
  3139.  * see bugs 330077 and 330078.
  3140.  *
  3141.  * To suppress the dialogs, you can run with the environment variable
  3142.  * XUL_ASSERT_PROMPT set to 0 (if unset, this defaults to 1).
  3143.  *
  3144.  * @param condition represents the condition that we're asserting to be
  3145.  *                  true when we call this function--should be
  3146.  *                  something that can be evaluated as a boolean.
  3147.  * @param message   a string to be displayed upon failure of the assertion
  3148.  */
  3149.  
  3150. function NS_ASSERT(condition, message) {
  3151.   if (condition)
  3152.     return;
  3153.  
  3154.   var releaseBuild = true;
  3155.   var defB = Components.classes["@mozilla.org/preferences-service;1"]
  3156.                        .getService(Components.interfaces.nsIPrefService)
  3157.                        .getDefaultBranch(null);
  3158.   try {
  3159.     switch (defB.getCharPref("app.update.channel")) {
  3160.       case "nightly":
  3161.       case "beta":
  3162.       case "default":
  3163.         releaseBuild = false;
  3164.     }
  3165.   } catch(ex) {}
  3166.  
  3167.   var caller = arguments.callee.caller;
  3168.   var assertionText = "ASSERT: " + message + "\n";
  3169.  
  3170.   if (releaseBuild) {
  3171.     // Just report the error to the console
  3172.     Components.utils.reportError(assertionText);
  3173.     return;
  3174.   }
  3175.  
  3176.   // Otherwise, dump to stdout and launch an assertion failure dialog
  3177.   dump(assertionText);
  3178.  
  3179.   var stackText = "";
  3180.   if (gTraceOnAssert) {
  3181.     stackText = "Stack Trace: \n";
  3182.     var count = 0;
  3183.     while (caller) {
  3184.       stackText += count++ + ":" + caller.name + "(";
  3185.       for (var i = 0; i < caller.arguments.length; ++i) {
  3186.         var arg = caller.arguments[i];
  3187.         stackText += arg;
  3188.         if (i < caller.arguments.length - 1)
  3189.           stackText += ",";
  3190.       }
  3191.       stackText += ")\n";
  3192.       caller = caller.arguments.callee.caller;
  3193.     }
  3194.   }
  3195.  
  3196.   var environment = Components.classes["@mozilla.org/process/environment;1"].
  3197.                     getService(Components.interfaces.nsIEnvironment);
  3198.   if (environment.exists("XUL_ASSERT_PROMPT") &&
  3199.       !parseInt(environment.get("XUL_ASSERT_PROMPT")))
  3200.     return;
  3201.  
  3202.   var source = null;
  3203.   if (this.window)
  3204.     source = this.window;
  3205.   var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].
  3206.            getService(Components.interfaces.nsIPromptService);
  3207.   ps.alert(source, "Assertion Failed", assertionText + stackText);
  3208. }
  3209.